简体   繁体   中英

Creating mixed Bar Chart with ReactJS using recharts or react-chartjs-2

image screen shot I am trying to implement multiple Bar chart for the below requirement of chart in ReactJS using recharts or react-chartjs-2 library. I was unable to find any direct solution available. Any suggestions how to create a similar type of chart

const data = [ { type: "Sample 1", data: [600, 400, 200, 800] }, { type: "Sampel 2", data: [700, 300, 600, 600] }, { type: "Total", data: [1300, 700, 800, 1400] } ];

The main requirement can be met by defining two xAxes , one for the individual values ( 'x1' ), the other one for the total bar ( 'x2' ).

For further details, please consult the chapter "Creating Multiple Axes" from Chart.js documentation

Please take a look at below code sample and see how it works. While this is a pure JavaScript solution, the concept should also work for react-chartjs-2 .

 const data = [{ type: "Sample 1", data: [600, 400, 200, 800] }, { type: "Sampel 2", data: [700, 300, 600, 600] }, { type: "Total", data: [1300, 700, 800, 1400] }]; new Chart('myChart', { type: "bar", data: { labels: ["A", "B", "C", "D"], datasets: [{ label: data[0].type, xAxisID: 'x1', data: data[0].data, backgroundColor: 'rgb(54, 162, 235)', barPercentage: 1 }, { label: data[1].type, xAxisID: 'x1', data: data[1].data, backgroundColor: 'rgb(255, 159, 64)', barPercentage: 1 }, { label: data[2].type, xAxisID: 'x2', data: data[2].data, backgroundColor: 'rgb(172, 215, 250)', barPercentage: 1 } ] }, options: { legend: { labels: { filter: item => item.text,= 'Total' } }: scales: { yAxes: [{ ticks: { min, 0: stepSize, 200 } }]: xAxes: [{ id, 'x1' }: { id, 'x2': display, false: offset; true } ] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <canvas id="myChart" height="90"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM