使用 recharts 或 react-chartjs-2 使用 ReactJS 创建混合条形图

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

image screen shot 我正在尝试使用 recharts 或 react-chartjs-2 库在 ReactJS 中实现多个条形图以满足以下图表要求。 我无法找到任何可用的直接解决方案。关于如何创建类似类型的图表的任何建议

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] } ];

可以通过定义两个 xAxes 来满足主要要求,一个用于单个值 ('x1'),另一个用于总条 ('x2')。

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

请查看下面的代码示例,看看它是如何工作的。虽然这是一个纯粹的 JavaScript 解决方案,但该概念也适用于 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>