如何对轴标签进行格式化?

152 阅读1分钟

如图,当轴标签数值精度有问题,非常长的时候,可以进行格式化吗?

解决方案

不同图表库对格式化的支持方式不一样,对于VChart而言,这里产生浮点数精度问题是因为在实现坐标轴刻度对齐的时候,进行浮点数的加法运算带来的。为了提高轴标签的可读性,可以通过label.formatMethod对轴标签进行格式化处理。

代码示例

const spec = {
  type: 'common',
  seriesField: 'color',
  data: [
    {
      id: 'id0',
      values: [
        { x: '周一', type: '早餐', y: 0.1633 },
      ]
    },
    {
      id: 'id1',
      values: [
        { x: '周一', type: '饮料', y: -0.3455 },
       
      ]
    }
  ],
  series: [
    {
      type: 'line',
      id: 'line',
      dataIndex: 0,
      label: { visible: true },
      seriesField: 'type',
      dataIndex: 0,
      xField: ['x', 'type'],
      yField: 'y'
    },
    {
      type: 'line',
      id: 'line',
      dataIndex: 1,
      label: { visible: true },
      seriesField: 'type',
      xField: 'x',
      yField: 'y',
      stack: false
    }
  ],
  axes: [
    { orient: 'left', seriesIndex: [0], id: 'left' },
    { 
      orient: 'right', 
      seriesId: ['line'], 
      grid: { visible: false }, 
      label: {
        formatMethod: (label) => {
          return Math.round(label * 100) / 100;
        }
      },
      sync: {
        axisId: 'left',
        tickAlign: true
      } 
    },
    { orient: 'bottom', label: { visible: true }, type: 'band' }
  ],
  legends: {
    visible: true,
    orient: 'bottom'
  }
};

const vchart = new VChart(spec, { dom: CONTAINER_ID });
vchart.renderSync();

// Just for the convenience of console debugging, DO NOT COPY!
window['vchart'] = vchart;

结果展示

相关文档

相关配置:www.visactor.io/vchart/opti…

Axes坐标轴教程: www.visactor.io/vchart/guid…

github:github.com/VisActor/VC…