Chartjs-Chart js same label, multi data

0👍

A very quick and dirty method would be to use a paired array that has the values you want to disaply for each data point at the same index point

i.e. var supportingData = [12, 14, 15, 16, 17, 26];

then in the onAnimation complete use the index of the current data set to draw out the data form this array at the same time

dataset.bars.forEach(function(bar, index) {
        //keep a refence of the fillstyle to change back to later
        var ctxColour = ctx.fillStyle;
        ctx.fillText(bar.value, bar.x, bar.y - 5);
        ctx.fillStyle = "#FF0000";

        ctx.fillText("$" + supportingData[index], bar.x + (ctx.measureText(bar.value).width)+10, bar.y - 5);
        //reset the fill style
        ctx.fillStyle = ctxColour;
});

because this is chartjs 1.x I do not think extra data you give to the chart is passed to the actual chart so if you wanted something a bit nicer you would need to extend your own chart and allow it to take this extra supporting data, but the method for displaying would be the same

var chartData = {
  labels: ["January", "February", "March", "April", "May", "June"],
  datasets: [{
    fillColor: "#79D1CF",
    strokeColor: "#79D1CF",
    data: [60, 80, 81, 56, 55, 40]
  }]
};
//add an array to have your paird data in
var supportingData = [12, 14, 15, 16, 17, 26];

var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
  showTooltips: false,
  onAnimationComplete: function() {

    var ctx = this.chart.ctx;
    ctx.font = this.scale.font;
    ctx.fillStyle = this.scale.textColor
    ctx.textAlign = "center";
    ctx.textBaseline = "bottom";

    this.datasets.forEach(function(dataset) {
      dataset.bars.forEach(function(bar, index) {
        //keep a refence of the fillstyle to change back to later
        var ctxColour = ctx.fillStyle;
        ctx.fillText(bar.value, bar.x, bar.y - 5);
        ctx.fillStyle = "#FF0000";
        
        ctx.fillText("$" + supportingData[index], bar.x + (ctx.measureText(bar.value).width)+10, bar.y - 5);
        //reset the fill sty;e
        ctx.fillStyle = ctxColour;
      });
    })
  }
});
<script src="https://rawgit.com/nnnick/Chart.js/v1.0.2/Chart.min.js"></script>
<canvas id="myChart2" height="300" width="500"></canvas>

Leave a comment