amcharts5 - format values in tooltips with a custom function

499 Views Asked by At

I'm using amcharts5 to represent some data. At a certain point I have a series where I want to display the tooltip differently from the original value.

Let's say for example my chart is something like this:

var series2 = chart.series.push(
  am5xy.LineSeries.new(root, {
    name: "Expenses",
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "expenses",
    categoryXField: "year",
    tooltip: am5.Tooltip.new(root, {
      pointerOrientation: "horizontal",
      labelText: "{name} in {categoryX}: {valueY} {info}"
    })
  })
);

I would like to setup things like:

labelText: "{name}: {Math.abs(valueY)} $"

or

labelText: "{name}: {2*valueY} $"

or

labelText: "{name}: {customFunction(valueY)} $"

but none of these works.

https://jsfiddle.net/2eb59g07/

I've read the documentation but I'm confused, between amcharts4 and 5 things changed a bit and while one documentation talks about number formatter the other talks about formatter as custom function. But there's no available clear examples of how this thing is implemented in the code of the v5 version.

1

There are 1 best solutions below

2
On

There is a setting called tooltipText using which you can format the tooltip text using a string template that can include placeholders for dynamic values.

Below the the tooltipText property is set to a string template that includes placeholders for the series name and the valueY field, which represents the y-value of each data point.

var series2 = chart.series.push(
  am5xy.LineSeries.new(root, {
    name: "Expenses",
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "expenses",
    categoryXField: "year",
    tooltip: am5.Tooltip.new(root, {
      pointerOrientation: "horizontal",
      formatter: function (value, info) {
        return Math.abs(value) + " $";
      }
    }),
    tooltipText: "{name}: {valueY}"
  })
);

CODE DEMO

EDIT:

As per your new requirement, you can just add adapters on labelText to get it done. Something like below:

series2.get("tooltip").label.adapters.add("text", function(text, target) {
    text = "";
    var tooltipDataItem = series2?.get("tooltipDataItem");
    text += series2?.get("name") + " : $" + customFun(tooltipDataItem?.get("valueY")); // Edit the text as per requirement.
    return text
  });

CODE DEMO