如何在 Chart.js 中的堆叠条形图后面制作基线条形图?

问题描述 投票:0回答:1

我正在尝试在 Chart.js 中创建一个堆积条形图,其中一个特定的条形图(标记为“予想”-预测)充当基线或背景层。我们的目标是让这个栏在视觉上位于其他堆叠栏的后面,因此它就像一个“容器”,其他栏累积填充到其中。

或者用另一种方式解释,就像其他栏填充了主栏。然而,我正在努力将主栏堆放在它后面。

我使用以下示例创建了一个代码笔:https://codesandbox.io/p/sandbox/vigilant-wave-wnvsxn?file=%2Fsrc%2Fcomponents%2FEnergyUsageChart.js%3A22%2C1-88%2C1

  const chartData = {
    labels: ["今日"], // Only today
    datasets: [
      {
        label: "prediction",
        data: [1200], // Only data for today
        backgroundColor: "rgba(237, 239, 255, 0.5)",
        borderColor: "rgba(106, 122, 242, 1)",
        borderWidth: 1,
        borderDash: [5, 5],
        stack: "baseline",
      },
      {
        label: "air-c",
        data: [300],
        backgroundColor: "rgba(88, 181, 247, 1)",
        stack: "filling",
      },
      {
        label: "illumination",
        data: [300],
        backgroundColor: "rgba(71, 68, 222, 1)",
        stack: "filling",
      },
      {
        label: "cooling-case",
        data: [300],
        backgroundColor: "rgba(157, 201, 210, 1)",
        stack: "filling",
      },
      {
        label: "others",
        data: [100],
        backgroundColor: "rgba(182, 193, 200, 1)",
        stack: "filling",
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: { stacked: true },
      y: {
        stacked: true,
        max: 2000,
        ticks: { stepSize: 1000 },
      },
    },
    plugins: {
      legend: { display: false },
      datalabels: { display: false },
      tooltip: {
        callbacks: {
          label: (context) => {
            const label = context.dataset.label || "";
            return `${label}: ${new Intl.NumberFormat("ja-JP", {
              style: "currency",
              currency: "JPY",
            }).format(context.parsed.y)}`;
          },
        },
      },
    },
  };

谢谢!

javascript reactjs chart.js
1个回答
0
投票

对于“基线”对象,您应该添加

grouped
属性和
false
来实现结果。

{
    label: "prediction",
    data: [1200], // Only data for today
    backgroundColor: "rgba(237, 239, 255, 0.5)",
    borderColor: "rgba(106, 122, 242, 1)",
    borderWidth: 1,
    borderDash: [5, 5],
    stack: "baseline",
    grouped: false,
},

演示@代码沙箱

© www.soinside.com 2019 - 2024. All rights reserved.