19

When using the Chart.js library, I can add multiple doughnuts on my page without a problem.

http://www.chartjs.org/docs/#doughnut-pie-chart

But I cannot find a way to always show the tooltips - not only when hovering the mouse over the doughnut. Does anybody know if this is possible?

Taapo
  • 1,785
  • 4
  • 18
  • 35

5 Answers5

43

I had the same problem today and solved it quite easy by adding the options onAnimationComplte and tooltipevents.

onAnitmationComplete calls the method to show the tooltips like a hover event does. Normally you define the events in tooltipevents to display the tooltips but we need to remove them and pass an empty array.

Note:(http://www.chartjs.org/docs/#doughnut-pie-chart).

Javascript:

var options = 
{
    tooltipTemplate: "<%= value %>",

    onAnimationComplete: function()
    {
        this.showTooltip(this.segments, true);

        //Show tooltips in bar chart (issue: multiple datasets doesnt work http://jsfiddle.net/5gyfykka/14/)
        //this.showTooltip(this.datasets[0].bars, true);

        //Show tooltips in line chart (issue: multiple datasets doesnt work http://jsfiddle.net/5gyfykka/14/)
        //this.showTooltip(this.datasets[0].points, true);  
    },

    tooltipEvents: [],

    showTooltips: true
}

var context = $('#chart').get(0).getContext('2d');
var chart = new Chart(context).Pie(data, options);  

HTML:

<div id="chartContainer">
    <canvas id="chart" width="200" height="200"></canvas>
</div>

Example Data:

var data = [
    {
        value: 300,
        color:"#F7464A",
        highlight: "#FF5A5E"
    },
    {
        value: 50,
        color: "#46BFBD",
        highlight: "#5AD3D1"
    },
    {
        value: 100,
        color: "#FDB45C",
        highlight: "#FFC870"
    }
]

JSFiddle PIE: http://jsfiddle.net/5gyfykka/

JSFiddle BAR/LINE: http://jsfiddle.net/5gyfykka/14/

Kapi
  • 547
  • 5
  • 11
  • Where did you get chart object? Do you first create the chart and then you set the options? – kentverger Sep 30 '14 at 16:54
  • 1
    @kentverger Yes, I changed the code so you can see how i solved it. – Kapi Oct 01 '14 at 07:47
  • 2
    Just to build on that example, swap out "chart.showTooltip(chart.segments, true);" with "this.showTooltip(this.segments, true);" ...then you don't need to worry about naming conventions :) – Delmontee Oct 20 '14 at 08:42
  • @Kapi this code seems to work well only with Pie Charts, any clue to have the same for line/bar charts ? – manish Nov 20 '14 at 07:10
  • 1
    @manish, yes this is possible check this fiddle: http://jsfiddle.net/5gyfykka/14/. Multiple datasets dont work yet but i will try to figure this out in the near future. – Kapi Nov 24 '14 at 12:15
  • @Kapi Were you able to get multiple datasets working? – wegelagerer Jun 24 '15 at 12:26
  • How i can make this work with Doughnut?? its not working for me :( – Ant Mar Aug 25 '15 at 07:35
  • I suggest the following solution **bar chart - multiple datasets** https://github.com/nnnick/Chart.js/issues/327#issuecomment-135493617 – Robin Gomez Aug 27 '15 at 17:14
  • @Kapi it works. but i overlaps on other tooltip. How to solve this? Please find solution for http://stackoverflow.com/questions/34282538/chart-js-avoid-overlapping-of-tooltips-in-pie-chart question – Guru Dec 15 '15 at 07:17
  • can we use `onComplete` call back instead of `onAnimationComplete`? – techie_28 Aug 24 '16 at 07:06
  • Is there a way to implement the same in Angular version? https://jtblin.github.io/angular-chart.js/#doughnut-chart – Vel Murugan S Nov 26 '16 at 14:39
  • The JSFiddle's are no longer working =(. It is important to use a resource link to an specific version of the Chart.js next time. – adelriosantiago Aug 29 '17 at 19:26
  • Working JSFiddles: http://jsfiddle.net/z8brxL9p/ and http://jsfiddle.net/swrqLuvj/ – adelriosantiago Sep 04 '17 at 21:32
  • 2
    @adelriosantiago this approach does not work with 2.x version. I am working on AngularChart which uses 2.x version and have the similar issue. – Ravi Khambhati Oct 03 '17 at 19:52
13

You can do this by writing your own plugin which supports ChartJS version > 2.1.5.

Include the following code in your script:

// Show tooltips always even the stats are zero

Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      // create an array of tooltips
      // we can't use the chart tooltip because there is only one tooltip per chart
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });

      // turn off normal tooltips
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      // turn on tooltips
      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        // we don't actually need this since we are not animating tooltips
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

// Show tooltips always even the stats are zero

And then just use the following line in the options of any chart on which you want to show all the tooltips available.

showAllTooltips: true

Working Fiddle is given below

// Show tooltips always even the stats are zero

Chart.pluginService.register({
  beforeRender: function(chart) {
    if (chart.config.options.showAllTooltips) {
      // create an array of tooltips
      // we can't use the chart tooltip because there is only one tooltip per chart
      chart.pluginTooltips = [];
      chart.config.data.datasets.forEach(function(dataset, i) {
        chart.getDatasetMeta(i).data.forEach(function(sector, j) {
          chart.pluginTooltips.push(new Chart.Tooltip({
            _chart: chart.chart,
            _chartInstance: chart,
            _data: chart.data,
            _options: chart.options.tooltips,
            _active: [sector]
          }, chart));
        });
      });

      // turn off normal tooltips
      chart.options.tooltips.enabled = false;
    }
  },
  afterDraw: function(chart, easing) {
    if (chart.config.options.showAllTooltips) {
      // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
      if (!chart.allTooltipsOnce) {
        if (easing !== 1)
          return;
        chart.allTooltipsOnce = true;
      }

      // turn on tooltips
      chart.options.tooltips.enabled = true;
      Chart.helpers.each(chart.pluginTooltips, function(tooltip) {
        tooltip.initialize();
        tooltip.update();
        // we don't actually need this since we are not animating tooltips
        tooltip.pivot();
        tooltip.transition(easing).draw();
      });
      chart.options.tooltips.enabled = false;
    }
  }
});

// Show tooltips always even the stats are zero


var canvas = $('#myCanvas2').get(0).getContext('2d');
var doughnutChart = new Chart(canvas, {
  type: 'doughnut',
  data: {
    labels: [
      "Success",
      "Failure"
    ],
    datasets: [{
      data: [45, 9],
      backgroundColor: [
        "#1ABC9C",
        "#566573"
      ],
      hoverBackgroundColor: [
        "#148F77",
        "#273746"
      ]
    }]
  },
  options: {
    // In options, just use the following line to show all the tooltips
    showAllTooltips: true
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
     <canvas id="myCanvas2" width="350" height="296"></canvas>
</div>

Working JSFIDDLE here.

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
6

I expanded on Kapi's method so when you hover over it you still get to keep the default functionality like color change, and when you hover over a section it will hide the rest. I think it looks better.

var options =
{
    onAnimationComplete: function () {
        this.showTooltip(this.segments, true);
    },        
}

var ctx = document.getElementById("Chart").getContext("2d");
var myPieChart = new Chart(ctx).Pie(data, options);

$("#Chart").on('mouseleave', function (){
    myPieChart.showTooltip(myPieChart.segments, true);
});
Indy411
  • 3,666
  • 4
  • 20
  • 19
1

In case someone tries to hide some of the segment tooltips; do it in the tooltipTemplate:

tooltipTemplate : "<%  var percentage = Math.round(circumference / 6.283 * 100); if (percentage >8)%><%= percentage %>%";

for example this code checks for the %value and only displays values higher than 8% to decrease clutter

ardavar
  • 510
  • 9
  • 20
0

If you want to display just ONE tooltip, you have to use this code. Here is exaple for first segment.

chart.showTooltip([chart.segments[0]], true);

Function showTooltip only accepts 2 dimensional arrays for first parameter.

Jan Šafránek
  • 893
  • 10
  • 13