Search code examples
cssreactjsfrontendchart.jsreact-chartjs-2

How can I achieve something like this image with chart.js(react-chartjs-2)?


enter image description here

Is it possible to achieve this -

  1. Different colour in the same bar
  2. Color length proportional to % of data available in that year

In total there are 4 years and I want to partition each bar into a maximum of 4 parts (can be 1, 2, 3 or 4 parts depending on years selected).


Solution

  • What you are searching for is something called "Stacked Bar Chart". This kind of chart can be used with the library you mentioned.

    As in the documentation:

    Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces.

    Here an example taken from the documentation:

    var stackedBar = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: {
            scales: {
                x: {
                    stacked: true
                },
                y: {
                    stacked: true
                }
            }
        }
    });
    

    Please, for more details refer to this section of the documentation:

    https://www.chartjs.org/docs/next/charts/bar/#stacked-bar-chart