Chartjs-ChartJS – Highlight grouped bars

0👍

You can extend the bar chart to draw the highlight over the columns. It would be better to make the start from highlight an option that you can pass in (highlightFromIndex in the below code)

HTML

<canvas id="myChart" width="400" height="200"></canvas>

JS

Chart.types.Bar.extend({
    name: "BarAlt",
    draw: function () {
        Chart.types.Bar.prototype.draw.apply(this, arguments);

        // overlay the highlight
        var ctx = this.chart.ctx;
        var scale = this.scale;
        var xColumnWidth = (scale.width - scale.xScalePaddingLeft - scale.xScalePaddingRight) / scale.xLabels.length
        ctx.fillStyle = 'rgba(255, 0, 0, 0.1)'
        ctx.fillRect(
            scale.xScalePaddingLeft + xColumnWidth * this.options.highlightFromIndex,
            scale.startPoint,
            xColumnWidth * (scale.xLabels.length - this.options.highlightFromIndex + 1),
            scale.endPoint - scale.startPoint)
    }
});


var ctx = $("#myChart").get(0).getContext("2d");

var gpdData = {
    "labels": ["2013", "2014", "2015", "2016"],
    "datasets": [
        {
            "label": "China",
            "fillColor": "rgba(220,220,220,0.5)",
            "strokeColor": "rgba(220,220,220,0.8)",
            "highlightFill": "rgba(220,220,220,0.75)",
            "highlightStroke": "rgba(220,220,220,1)",
            "data": [0.5, 11, 2, 3]
        },
        {
            "label": "India",
            "fillColor": "rgba(151,187,205,0.5)",
            "strokeColor": "rgba(151,187,205,0.8)",
            "highlightFill": "rgba(151,187,205,0.75)",
            "highlightStroke": "rgba(151,187,205,1)",
            "data": [1, 9, 4, 6]
        }
    ]
}

var myBarChart = new Chart(ctx).BarAlt(gpdData, {
    highlightFromIndex: 3
});

Fiddle – http://jsfiddle.net/smLcr3v4/

Leave a comment