[Chartjs]-Allow display of multiple data attributes in tooltip of Chart.js

3👍

react-chartjs currently depends on Chart.js v1.1.1 – which does not allow the multiple lines in tooltip.

  1. Tweaking the Chart.js file

(this method is not recommended, its only a hack)If you ‘have’ to use react-chartjs, you can do the following. You can send a custom tooltip template as an option (they use John Resig’s micro templating: see it here)

options = {
    tooltipTemplate: "<%=label%>:<%= value %><%\n%><%=value1string%>:<%= value1%><%\n%><%=value2string%>:<%= value2 %>",
}

But wait, for this method, there are many catches (:P and you follow them all to get it working).

  • The data value1, value1string, value2, value2string have to be global variables for the function in the file Chart.js to access them.

  • If you look at the micro templating engine in the above mentioned blog, you can see that ‘\n’ character is replaced by a ” ” (space). So the above tooltip template will give all the data in one line. To get the intended behaviour, you need to modify the code in the source file from

(in Chart.js file)

 .replace(/[\r\t\n]/g, ” “)

to

.replace(/[\r\t]/g, ” “)
  1. Other third-party libraries

There are many other third-party libraries that do what is required.

Using react-chartjs-2. This is a wrapper on Chart.js v2.x. You can use the callbacks in option provided by Chart.js to achieve it. See this example for usage.

var options={
    tooltips: {
        mode: 'label',
        callbacks: {
            afterLabel: function() {
                return 'whatever you want to display';
            },
        },
    },
}

Using fusioncharts. The library is actually pretty neat and give a very good control over the elements in a plot. You can easily configure the tooltip to act as you want. The only downside of this library is, it’s free only for person use.

Using react-d3-tooltip. This library also gives a good amount of control over the elements, go through the docs. You can customize the tooltip as you want.

Hope it helps!

Leave a comment