0
votes

So I have created a line chart using Chart.js but I want to add some custom text to each individual tooltip.

Chart Example

I want to be able to change the "Player 2: 29" text to "Custom Name: 29" and the "Player 2: 44" to "Different Custom Name: 29".

I pass a json object to the view which is where I get the point values (which works fine), but the json object also has a string value which is what I want to use to in place of "Custom Name".

More detail on scenario:

  • The green line represents one team and the red line is the other team.
  • There are four players in a team
  • Each point on the chart represents a players score which is why I want to be able to display the persons name along with their score in the tooltip.
  • Each tooltip would contain 2 different players names and score.

Is there any way to do this?

Thanks for taking the time to read this far.

1
I found this link which helped me out greatly stackoverflow.com/questions/27590397/… - Bad Dub

1 Answers

2
votes

Custom Labels for Each Dataset

You can do this by using a custom label object.


Preview

enter image description here


Script

function TeamPlayerLabel(label, team1Label, team2Label) {
    this.label = label;
    this["Team 1"] = team1Label;
    this["Team 2"] = team2Label;
}
TeamPlayerLabel.prototype.toString = function () {
    return this.label;
}

var data = {
    labels: [
        new TeamPlayerLabel("Player 1", "John Red", "John Green"),
        new TeamPlayerLabel("Player 2", "Mark Red", "Mark Green"),
        new TeamPlayerLabel("Player 3", "Jane Red", "Jane Green"),
        new TeamPlayerLabel("Player 4", "Jill Red", "Jill Green"),
    ],
    datasets: [
        {
            label: "Team 1",
            ...
        },
        {
            label: "Team 2",
            ...
        }
    ]
};

and then

new Chart(ctx).Line(data, {
    multiTooltipTemplate: function (self) {
        return self.label[self.datasetLabel] + ': ' + self.value;
    }
});

Fiddle - https://jsfiddle.net/htq3kgay/