如何使用 Chart.JS 创建堆积条形图/水平图?

How is it possible to create a stacked bar / horizontal chart with Chart.JS?

我可以使用 Chart.JS 创建 "traditional" 条形图,甚至可以创建如下所示的堆积条形图:

但我需要创建一个水平而非垂直条形图,并在底部显示百分比,如下图所示 this example 使用 xlsxwriter 创建的:

如何操纵 Chart.JS 来执行此命令的魔法?

更新

我将答案标记为正确,因为它显然有效,基于 jsfiddle。但是我一直无法将数据堆叠起来。这是我看到的:

这是我的代码:

var ctxBarChart = $("#priceComplianceBarChart").get(0).getContext("2d");
var barChartData = {
    labels: ["Bix Produce", "Capitol City", "Charlies Portland", "Costa Fruit and Produce", "Get Fresh Sales", "Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"],
    datasets: [
        {
            label: "Price Compliant",
            backgroundColor: "rgba(34,139,34,0.5)",
            hoverBackgroundColor: "rgba(34,139,34,1)",
            data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027, 25553]
        },
        {
            label: "Non-Compliant",
            backgroundColor: "rgba(255, 0, 0, 0.5)",
            hoverBackgroundColor: "rgba(255, 0, 0, 1)",
            data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
        }
    ]
}

var optionsBar = {
    options: {
        scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
};

var priceBarChart = new Chart(ctxBarChart, {
    type: 'horizontalBar',
    data: barChartData,
    options: optionsBar
});

我做错了什么?

注意:我也试过这个:

var optionsBar = {
    stacked: true
};

...还有这个(系腰带背带裤):

var optionsBar = {
    stacked: true,
    options: {
        scales: {
            xAxes: [{
                stacked: true
            }],
            yAxes: [{
                stacked: true
            }]
        }
    }
};

更新 3

这有效(我不得不剥离其中一个选项级别):

var optionsBar = {
    scales: {
        xAxes: [{
            stacked: true
        }],
        yAxes: [{
            stacked: true
        }]
    }
};
  1. 如果您想创建水平条而不是常规字符,您可以使用 type: 'horizontalBar'
  2. 要将图表创建为 "stacked bar",您需要设置


xAxes: [{
    stacked: true
}],
yAxes: [{
    stacked: true
}]

您可以使用此代码:

var config = {
  type: 'horizontalBar',
  data: {
    labels: ["A", "B", "C", "D", "E"],
    datasets: [{
      label: "Dataset 1",
      backgroundColor: "rgba(154,178,96,0.5)",
      hoverBackgroundColor: "rgba(154,178,96,1)",
      data: [10, 15, 5, 81, 55],
    }, {
      label: "Dataset 2",
      backgroundColor: "rgba(197,213,167,0.5)",
      hoverBackgroundColor: "rgba(197,213,167,1)",
      data: [90, 85, 95, 19, 45]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    }
  }
};

var ctx = document.getElementById("myChart").getContext("2d");
new Chart(ctx, config);

这是一个工作示例:
https://jsfiddle.net/0xLxum4s/

(出于某种原因,它在 so 片段中不起作用,所以我使用了 jsfiddle)。