You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ChartJS混合图表未按标签拆分数据集问题求助

问题分析与解决

你的问题出在数据集的data数组长度和labels不匹配,每个数据集的data数组元素数量需要和labels的数量(2个)一一对应,ChartJS才能把图表渲染到对应的标签列下。当前每个dataset的data只有1个元素,所以所有图表都挤在了第一个标签的位置。

修正后的代码

import { BoxPlotChart } from "@sgratzl/chartjs-chart-boxplot";

const chart = new BoxPlotChart(ctx, {
  data: {
    labels: ["io_current", "usage_bytes"],
    datasets: [
      {
        label: "io_current",
        type: "boxplot",
        borderColor: "green",
        backgroundColor: "rgb(128, 222, 234, 0.5)",
        outlierBackgroundColor: "rgb(128, 222, 234, 0.5)",
        data: [
          {
            min: 64,
            max: 458,
            median: 252,
            q1: 86,
            q3: 436,
            outliers: [43, 480],
            whiskerMin: 64,
            whiskerMax: 458,
          },
          null // 对应第二个标签,留空不渲染
        ],
      },
      {
        label: "io_current",
        type: "bar",
        backgroundColor: "rgb(227, 185, 0)",
        data: [[152, 370], null], // 第二个标签位置留空
      },
      {
        label: "usage_bytes",
        type: "boxplot",
        borderColor: "green",
        backgroundColor: "rgb(128, 222, 234, 0.5)",
        outlierBackgroundColor: "rgb(128, 222, 234, 0.5)",
        data: [
          null, // 第一个标签位置留空
          {
            min: 50,
            max: 414,
            median: 218,
            q1: 70,
            q3: 394,
            outliers: [30, 435],
            whiskerMin: 50,
            whiskerMax: 414,
          },
        ],
      },
      {
        label: "usage_bytes",
        type: "bar",
        backgroundColor: "rgb(227, 185, 0)",
        data: [null, [131, 333]], // 第一个标签位置留空
      },
    ],
  }
});

关键调整说明

  • 每个dataset的data数组长度必须和labels数组长度一致(这里是2个元素)
  • 对于只属于某个标签的图表,在对应标签的位置放数据,其他位置用null占位,告诉ChartJS不在该列渲染这个数据集
  • 调整后,io_current的箱线图和柱状图会显示在第一列,usage_bytes的对应图表会显示在第二列,实现预期布局

内容的提问来源于stack exchange,提问作者Seth Lutske

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:29:54