在 Chart.js 中创建分组和堆叠图表

Dus*_*y04 4 chart.js

我想知道是否可以在Chart js中创建分组和堆叠图表。

我有两组数据,每组数据都有正(收入)和负(税收)成分,因此希望将它们“堆叠”在一起。我还展示了两个数据案例 - 一个基础案例和敏感案例,因此希望将每个案例“分组”在一起。

如果数据沿 x 轴堆叠,则条形重叠,如果数据未堆叠,则正(收入)条形与其对应的负(税收)条形偏移 - 此切换可以在下面的代码中的“堆叠”下看到' 选项。

我想将收入和税收部分叠加在一起,并将每年的两个案例放在一起,以便可以整齐地显示图表。这可能吗?任何帮助或见解将不胜感激。

我的图表的代码如下:

new Chart(document.getElementById("MyChart"), {
    type: 'bar',
    data: {
      labels: [2017, 2018, 2019, 2020, 2021, 2022, 2023],
      datasets: [{
          label: "Income - Base",
          type: "bar",
		  backgroundColor: "#eece01",
		  data: [30, 31, 32, 33, 34, 35, 36],
        }, {
          label: "Income - Sensitivity",
          type: "bar",
		  backgroundColor: "#f8981f",
		  data: [20, 21, 22, 23, 24, 25, 26],
        }, {
          label: "Tax - Base",
          type: "bar",
          backgroundColor: "#87d84d",
          data:  [-15, -16, -17, -18, -19, -20, -21],
        }, {
          label: "Tax - Sensitivity",
          type: "bar",
          backgroundColor: "#00b300",
          backgroundColorHover: "#3e95cd",
          data: [-10, -11, -12, -13, -14, -15, -16]
        }
      ]
    },
		options: {
			scales: {		
				xAxes: [{
				    //stacked: true,
					stacked: false,
					ticks: {
						beginAtZero:true,
						maxRotation: 0,
						minRotation: 0					
					}
				}],					
				yAxes: [{
				    stacked: false,
				}]
			},
		}
});
Run Code Online (Sandbox Code Playgroud)
<canvas id="MyChart" width="400" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)

Shi*_*fty 9

您可以通过stacked在 x 轴和 y 轴上将选项设置为 true来堆叠条形图,并定义stack数据集的组属性。

以下是您提出更改的片段:

new Chart(document.getElementById("MyChart"), {
  type: 'bar',
  data: {
    labels: [2017, 2018, 2019, 2020, 2021, 2022, 2023],
    datasets: [{
      label: "Income - Base",
      type: "bar",
      stack: "Base",
      backgroundColor: "#eece01",
      data: [30, 31, 32, 33, 34, 35, 36],
    }, {
      label: "Tax - Base",
      type: "bar",
      stack: "Base",
      backgroundColor: "#87d84d",
      data: [-15, -16, -17, -18, -19, -20, -21],
    }, {
      label: "Income - Sensitivity",
      type: "bar",
      stack: "Sensitivity",
      backgroundColor: "#f8981f",      
      data: [20, 21, 22, 23, 24, 25, 26],
    }, {
      label: "Tax - Sensitivity",
      type: "bar",
      stack: "Sensitivity",
      backgroundColor: "#00b300",
      backgroundColorHover: "#3e95cd",
      data: [-10, -11, -12, -13, -14, -15, -16]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        //stacked: true,
        stacked: true,
        ticks: {
          beginAtZero: true,
          maxRotation: 0,
          minRotation: 0
        }
      }],
      yAxes: [{
        stacked: true,
      }]
    },
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="MyChart" width="400" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)