c3js - having the X axis in the middle of the chart

人走茶凉 提交于 2019-12-10 22:31:39

问题


Is it possible to have the X axis in the middle of the graph?
When having Y values both negative and positive - and the X axis is on the 0 value
lets say similar to this image


回答1:


Positioning C3 x axis at a Desired y Value

Method 1

Note that this method won't work if you have a .load() - see Method 2.

You can override the chart's getTranslate function to do this, like so

// 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();

where chart is your C3 chart object


Fiddle - http://jsfiddle.net/3zpyu0yx/

Method 2

Method 1 won't work when the data changes - because c3 stores the transitions (including those for the axis) and uses them when redrawing. So it never calls our updated getTranslate position for the new data and we are stuck with an animation that positions the scale at the 0 position of the original dataset.

One way to work around this would be to wait for transition to complete and then manually translate our axis. OR better still we could just update the transition for the x axis, like 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) + ")")

where chart is the C3 chart object.

You call this when you need the chart axis update. For a .load(), that would be within the done callback.


Fiddle - http://jsfiddle.net/1hrd9g3k/




来源:https://stackoverflow.com/questions/32427892/c3js-having-the-x-axis-in-the-middle-of-the-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!