c3js - X轴位于图表中间

Boa*_*oaz 2 javascript c3.js

是否可以将X轴放在图形的中间?
当Y值为负值和正值 - 并且X轴为0时,
我们可以说与此图像类似

截图

pot*_*ngs 5

将C3 x轴定位在所需的y值

方法1

请注意,如果您有.load()- 请参阅方法2 ,此方法将不起作用.

您可以覆盖图表的getTranslate功能来执行此操作,就像这样

// get the original translate function
var originalTranslate = chart.internal.getTranslate;
chart.internal.getTranslate = function (target) {
    // if we are drawing the x axis
    if (target === 'x')
        // use the y scale to get the y position
        return "translate(" + 0 + "," + this.y(0) + ")"
    else
        // otherwise just call the original function
        return originalTranslate.apply(this, [ target ]);
}
// redraw
chart.flush();
Run Code Online (Sandbox Code Playgroud)

其中图表是您的C3图表对象


小提琴 - http://jsfiddle.net/3zpyu0yx/

方法2

方法1在数据更改时不起作用 - 因为c3存储转换(包括轴的转换)并在重绘时使用它们.因此,它永远不会调用我们更新getTranslate的新数据位置,我们会停留一个动画,将比例定位在原始数据集的0位置.

解决此问题的一种方法是等待转换完成,然后手动转换我们的轴.或者更好的是我们可以更新x轴的过渡,如o

// select the x axis
d3.select(chart.element).select('.' + c3.chart.internal.fn.CLASS.axisX).transition()
    // and translate it to the y = 0 position
    .attr('transform', "translate(" + 0 + "," + chart.internal.y(0) + ")")
Run Code Online (Sandbox Code Playgroud)

其中图表是C3图表对象.

您需要图表轴更新时调用此方法.对于a .load(),这将在done回调中.


小提琴 - http://jsfiddle.net/1hrd9g3k/


在此输入图像描述