amcharts4

AMCharts4 center 0 using XYChart with positive and negative values


Image of the chart I have a horizontal XYCharts with positive and negative values. I want to align the 0 value of the horizontal axis in the center of the page, independent of the values. Currently it shifts towards the right or the left, depending on the positive or negative values. How can I configure AMCharts4 to achieve this?

I search the AMCharts 4 documentation but couldn't find a solution.


Solution

  • Without seeing your code or even which chart style you're using, it's hard to give specific advice. Assuming you're using the amCharts XY Chart, here's one possible approach you should be able to adapt to your needs.

    1. Use the range of your data to find the maximum value:
    let maxValue = Math.max(Math.abs(Math.min(...data)), Math.max(...data));
    
    1. Set your chart's X axis "min" and "max" to be symmetrical around zero:
    // Create the chart
    let chart = am4core.create("chartdiv", am4charts.XYChart);
    
    // Set the data
    chart.data = data; // Replace with your actual data
    
    // Create the Y axis
    let categoryAxis = chart.yAxes.push(new am4charts.CategoryAxis());
    categoryAxis.dataFields.category = "category";
    categoryAxis.renderer.grid.template.location = 0;
    
    // Create the X axis
    let valueAxis = chart.xAxes.push(new am4charts.ValueAxis());
    valueAxis.min = -maxValue;
    valueAxis.max = maxValue;
    valueAxis.renderer.minGridDistance = 50;
    valueAxis.strictMinMax = true;
    
    // Create the series
    let series = chart.series.push(new am4charts.ColumnSeries());
    series.dataFields.valueX = "value";
    series.dataFields.categoryY = "category";
    series.columns.template.tooltipText = "{categoryY}: {valueX}";