How to create stacked bar chart using react-chartjs-2?
Asked Answered
K

2

9

I have to create stacked bar chart using react-chartjs-2.

options : {
    maintainAspectRatio: false,
    tooltips: {
      mode: 'x-axis'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true
      }]
    }
  }

The stacked in Bar doesn't seem to work.

I am using [email protected]

Klee answered 26/5, 2017 at 9:32 Comment(0)
E
12

 const options = {
       scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }

    let data ={ 
      datasets:[{
        label: 'test1',
          data :[1]
        },
        {
          label: 'test2',
          data:  [2]   
        }],
      labels:['label']
    }
    
    render(){
      return  <Bar  data={data} options={options} />
    }
Exorcist answered 5/6, 2017 at 12:17 Comment(2)
this doesn't work, you should add stack:"" on datasetsCathrin
it does work with chart.js 2.9.4, you must be using a newer versionVenous
H
11

Add the stack option to your datasets.

Identical stack values are stacked together.

const arbitraryStackKey = "stack1";
const data = {
  labels: ['a', 'b', 'c', 'd', 'e'],
  datasets: [
    // These two will be in the same stack.
    {
      stack: arbitraryStackKey,
      label: 'data1',
      data: [1, 2, 3, 4, 5]
    },
    {
      stack: arbitraryStackKey,
      label: 'data2',
      data: [5, 4, 3, 2, 1]   
    }
  ]
}
Holystone answered 10/12, 2018 at 21:45 Comment(1)
It works but can you explain what does stack: 'stack1' mean?Lit

© 2022 - 2024 — McMap. All rights reserved.