Search code examples
jquerychartstooltipchart.js

Custom label from using separate array in Chart JS


In my project, I am using Chart.JS to show the line chart.

Right now the tooltip in the graph showing like

Date: 01/02/2016

Price: 50

These data getting from two arrays. But I need to show one more data below the price. So the tooltip will be like

Date: 01/02/2016

Price: 50

Shop: Shop Name

How can I achieve this in Chart JS? Or is it possible with some other chart? Please help. My sample code to generate the graph is

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: {
    labels: data.day,
    datasets: [{
        label: 'Price Change',
        data: data.price,
        backgroundColor: "rgba(255,255,255,0.4)",
        borderColor: "rgba(0, 183, 255,0.4)",
        pointRadius: 5,
        pointBorderColor: "rgba(255,0,0,0.4)",
        pointBackgroundColor: "rgba(255,0,0,0.4)",
    }]
    },
    options: {
        tooltips: {
            enabled: true,
            mode: 'single',
            callbacks: {
                label: function(tooltipItems, data) { 
                    return 'Price: '+tooltipItems.yLabel;
                }
            }
        }
    }
    });

In the above code data.price is storing the price array. I need to pass the store details with it and show it in the tooltip.


Solution

  • you can storing your tooltips items in an array, and return back, it will show on the tooltips label.

    for example:

    callbacks: {
        label: function(tooltipItem, data) {
            var firstTooltip = "toolTipsIdx: " + tooltipItem.index;
            var otherTooltip = "Ylabel value: " + tooltipItem.yLabel;
            var tooltip = [firstTooltip, otherTooltip]; //storing all the value here
            return tooltip; //return Array back to function to show out
        }
    }