ChartJs 中具有多个部分的水平条

Jas*_*nle 5 javascript charts chart.js

我想创建一个包含 3 个部分的水平条形图。请参阅下面的图片: C

我已经做了很多工作(我猜:))我只是想弄清楚如何排列数据集,以便它们显示多个条形并以不同的颜色显示,如示例所示。

JavaScript 到目前为止:

        var ctx7 = document.getElementById('myChart7').getContext('2d');
        var myChart7 = new Chart(ctx7, { // eslint-disable-line
            type: 'horizontalBar',
            data: {
                labels: ['2018', '2019'],
                datasets: [{
                    label: '# of Votes',
                    data: [10, 19],
                    backgroundColor: [
                        'rgb(0,51,160)',
                        'rgb(26,121,191)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            fontColor: 'white',
                            beginAtZero: true,
                            fontSize: 18,
                        },
                        gridLines: {
                            display: false
                        }
                    }],
                    xAxes: [{
                        gridLines: {
                            display: false
                        },
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                },
                legend: {
                    display: false
                }
            }
        });
Run Code Online (Sandbox Code Playgroud)

tim*_*ton 6

这种绘图类型称为“堆积条形图”,包含在Chart.js 示例中。文档非常清楚

这是一个工作示例:

new Chart(document.getElementById("chart"), {
  type: "horizontalBar",
  data: {
    labels: ["A", "B"],
    datasets: [{
        data: [1, 4],
        backgroundColor: "#0033a0"
      },
      {
        data: [3, 1],
        backgroundColor: "#1a79bf"
      },
      {
        data: [2, 2],
        backgroundColor: "#b2b2b2"
      }
    ]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart"></canvas>
Run Code Online (Sandbox Code Playgroud)