问题
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