Normally, the X-axis will be shown at the bottom of the plot container, regardless of the Y-axis scale. This tutorial shows how we can make the X-axis dynamically position itself so that it sticks to the position of the zero value.
Code
The idea is to watch for various events that could affect position of the X-axis, then position it accordingly:
- Y axis was scaled.
- Size of the plot container changed.
- Position of the container with Y-axes and plot container changed.
// Configure axis
let xRenderer = xAxis.get("renderer");
xRenderer.labels.template.set("centerY", 0);
xRenderer.labels.template.set("paddingTop", 6);
xRenderer.set("strokeOpacity", 1);
// Set up events
yAxis.on("start", updateAxisPosition);
yAxis.on("end", updateAxisPosition);
chart.yAxesAndPlotContainer.events.on("positionchanged", updateAxisPosition);
chart.plotContainer.events.on("boundschanged", updateAxisPosition);
function updateAxisPosition() {
let plotHeight = chart.plotContainer.height();
let y = yAxis.get("renderer").positionToCoordinate(yAxis.valueToPosition(0)) - plotHeight;
if (y > 0) {
y = 0;
}
if (y < -plotHeight) {
y = -plotHeight;
}
xAxis.set("y", y);
}
// Configure axis
var xRenderer = xAxis.get("renderer");
xRenderer.labels.template.set("centerY", 0);
xRenderer.labels.template.set("paddingTop", 6);
xRenderer.set("strokeOpacity", 1);
// Set up events
yAxis.on("start", updateAxisPosition);
yAxis.on("end", updateAxisPosition);
chart.yAxesAndPlotContainer.events.on("positionchanged", updateAxisPosition);
chart.plotContainer.events.on("boundschanged", updateAxisPosition);
function updateAxisPosition() {
var plotHeight = chart.plotContainer.height();
var y = yAxis.get("renderer").positionToCoordinate(yAxis.valueToPosition(0)) - plotHeight;
if (y > 0) {
y = 0;
}
if (y < -plotHeight) {
y = -plotHeight;
}
xAxis.set("y", y);
}
Demo
See the Pen XAxis on 0 grid position by amCharts team (@amcharts) on CodePen.