Search code examples
javascriptchartsamchartsamcharts4

How to change the text of the y axis in amcharts


I'm trying to change the displayed values on the Y axis to be custom text, or adding text beside the value. Can I change the valueAxis text?

here is the code

// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

// Create chart instance
var chart = am4core.create("chartdiv", am4charts.XYChart);

// Add data
chart.data = [{
  "year": "2008",
  "label": 101
}, {
  "year": "2009",
  "label": 142
}, {
  "year": "2010",
  "label": 462
}, {
  "year": "2011",
  "label": 364
}, {
  "year": "2012",
  "label": 465
}];

....

// Create value axis
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
valueAxis.renderer.inversed = false;
valueAxis.title.text = "";
valueAxis.renderer.minLabelPosition = 0.001;

// Create series
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "label";
series1.dataFields.categoryX = "year";
series1.name = "Currency";
series1.strokeWidth = 3;
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{name} in {categoryX}: {valueY}";
series1.legendSettings.valueText = "{valueY}";
series1.visible  = false;

// Add chart cursor
chart.cursor = new am4charts.XYCursor();
chart.cursor.behavior = "zoomY";

// Add legend
chart.legend = new am4charts.Legend();

I want to change 200,300,400,500,600,700 and 800 to (as example) 200s,300s,400s,500s,600s,700s,800s ..

CodePen


Solution

  • A quick way is to use the numberFormatter and just add 's' to your number format, which will impact all numeric values in your chart (axis, tooltips, legend values, etc):

    chart.numberFormatter.numberFormat = "#'s'";
    

    It is important to include the quotes around the s in this case to escape it since it is a format modifier for absolute values.

    Alternatively, if you're just targeting the axis tooltip, use an adapter on getTooltipText

    valueAxis.adapter.add("getTooltipText", function(text, target, key) {
     return text + "s";
    });