2
votes

I am using Chart.js grouped bar chart. I want to show my bars with gradient colors. Currently it show as shown in below image. Any help will be greatly appreciated.

enter image description here

var rateOfReturn= document.getElementById("rateofreturn-chart-canvas").getContext('2d');

    var rateOfReturnData = {
        labels: ["Monthly", "Quarterly", "Semiannually", "Annually"],
        datasets: [
            {
                label: "label1",


                backgroundColor: [
                    '#26343b',
                    '#26343b',
                    '#26343b',
                    '#26343b'
                ],
                data: [4, 6, 8, -3],
            },
            {
                label: "",
                backgroundColor: [
                    '#be1a33',
                    '#be1a33',
                    '#be1a33',
                    '#be1a33'
                ],
                data: [6, 10, 11, 7],
            },
            {
                label: "",
                backgroundColor: [
                    '#00b786',
                    '#00b786',
                    '#00b786',
                    '#00b786'
                ],
                data: [13, 10, 9, 4],
            },
            {
                label: "",
                backgroundColor: [
                    '#f86929',
                    '#f86929',
                    '#f86929',
                    '#f86929'
                ],
                data: [6, 8, 2, 11],
            },
            {
                label: "",
                backgroundColor: [
                    '#046cd0',
                    '#046cd0',
                    '#046cd0',
                    '#046cd0'
                ],
                data: [4, 8, 7, 13],
            }

        ]

    };


    rateOfReturn.canvas.height = 80;
    var myBarChart = new Chart(rateOfReturn, {
        type: 'bar',
        data: rateOfReturnData,
        options: {
            legend:
            {
                display: false
            },
            scales:
            {
                xAxes: [{
                    title: "Test title",
                    ticks: {
                        beginAtZero: true,
                        titleFontWeight: "bold"
                    },

                }],
                yAxes: [{
                    scaleLabel: {
                        display: true,
                        labelString: 'Rate Of Return (ROR) %    '
                    },
                    ticks: {
                        beginAtZero:true,
                        mirror:false,
                        suggestedMin: 0
                    },
                }]
            }
        }
    });
1
@Keno The duplicate is useful for a single chart (line for instance) but when working with several bar charts, it is not as easy. And I think the OP is especially asking for this issue.tektiv
@Tektiv thats true. whereever i tried to found the solution provided was only for the single bar chart not for the group bar chartkd patel

1 Answers

4
votes

You want to use Chart.js plugins. They let you handle some events triggered through the chart creation such as the initialization, the resize, etc.

Chart.pluginService.register({
    beforeUpdate: function(chart) {
        // All the code added here will be executed before a chart update
    }
});

You also want to use createLinearGradient to create a gradient color usable in a canvas :

var gradient = ctx.createLinearGradient(0,0,200,0); // Dimensions of the color rectangle
gradient.addColorStop(0,"green"); // First color
gradient.addColorStop(1,"white"); // Second color

Now you want to use both into one. Let's first see how it works.

You first have to add the two colors of the gradient you want to see in your chart data :

datasets: [{
    label: "label1",
    backgroundColor: [
        ['#26343b', 'white'], // `white` and `#FFFFFF` both stand for a white color
        ['#26343b', 'white'],
        ['#26343b', 'white'],
        ['#26343b', 'white']
    ],
    data: [4, 6, 8, -3],
}, {
    // ...
}]

Then you need to add the following plugin before you create the chart (using new Chart()), or else it won't be added into the chart's plugin service :

Chart.pluginService.register({
    beforeUpdate: function(chart) {

        // For every dataset ...
        for (var i = 0; i < chart.config.data.datasets.length; i++) {

            // We store it
            var dataset = chart.config.data.datasets[i];

            // For every data in this dataset
            for (var j = 0; j < dataset.data.length; j++) {

                // We store the data model (graph information)
                var model = dataset._meta[0].data[j]._model;

                // We use the model to get the left & right borders X position 
                // and to create the gradient
                var start = model.x,
                    end = model.x + model.width,
                    gradient = rateOfReturn.createLinearGradient(start, 0, end - 5, 0);

                // The colors of the gradient that were defined in the data
                gradient.addColorStop(0, dataset.backgroundColor[j][0]);
                gradient.addColorStop(1, dataset.backgroundColor[j][1]);

                // We set this new color to the data background
                dataset.backgroundColor[j] = gradient;
            }
        }
    }
});

Follows the result of the plugin with your example, which you can find on this jsFiddle :

enter image description here