[Chartjs]-Chart.js: Display Custom Tooltips, always visible on stacked bar-chart

5👍

Assuming you’re referring to the percentage values in the bars, those are called labels, not tooltips (which are what appear when you mouse over an element).

Label functionality is not natively available in Chart.js but can be added via the datalabels plugin. You’ll need to include the plugin via a script tag. (After the script tag where you load Chart.js!)

The bar chart sample is already quite close to your desired result, but I’ve merged it with your code in the snippet below to help you along.

You can reference the plugin formatting documentation to tailor the final result.

var labelArray = ["James", "Mark", "Simon"],
  greenData = [55, 82, 32],
  orangeData = [27, 10, 53],
  greyData = [18, 8, 15];

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: labelArray,
    datasets: [{
        label: 'Green %',
        data: greenData,
        backgroundColor: 'rgb(0,166,149)',
        borderColor: 'rgb(0,166,149)',
        borderWidth: 1
      },
      {
        label: 'Orange %',
        data: orangeData,
        backgroundColor: 'rgb(229,117,31)',
        borderColor: 'rgb(229,117,31)',
        borderWidth: 1,
      },
      {
        label: 'Grey %',
        data: greyData,
        backgroundColor: 'rgb(179,179,179)',
        borderColor: 'rgb(179,179,179)',
        borderWidth: 1,
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: true
      }]
    },
    plugins: {
      datalabels: {
        color: 'white',
        font: {
          weight: 'bold'
        },
        formatter: function(value, context) {
          return Math.round(value) + '%';
        }
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<canvas id="myChart"></canvas>

Leave a comment