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

Chart.js能否程序化生成分组图表?分组展示方案优化咨询

服务器响应时间分组图表实现方案

问题背景

Web应用通过API采集多台服务器的响应时间,使用Chart.js v4展示时,希望按系统(PR1、EC1)分组展示对应服务器的数据。当前用0填充非对应系统的位置,导致视觉上出现其他系统服务器的颜色残留(0值的bar仍会占用空间并显示背景色)。

方案一:Chart.js v4 正确实现方式

核心是将非对应系统位置的0替换为null,Chart.js会忽略null值,不渲染对应的bar,从而避免颜色残留。同时配置图表确保分组展示效果。

修改后的数据结构

var data = {
  labels: ["PR1","EC1"],
  datasets: [
    {
      label: "pr1app1",
      backgroundColor: "blue",
      barThickness: 20,
      data: [3, null], // 非PR1系统用null替代0
    },
    {
      label: "pr1app2",
      backgroundColor: "red",
      barThickness: 20,
      data: [4, null],
    },
    {
      label: "pr1app3",
      backgroundColor: "green",
      barThickness: 20,
      data: [7, null],
    },
    {
      label: "ec1app1",
      backgroundColor: "yellow",
      barThickness: 20,
      data: [null, 15],
    },
  ],
};

图表配置

var options = {
  responsive: true,
  scales: {
    x: {
      stacked: false, // 关闭堆叠,实现分组展示
      barPercentage: 0.8, // 调整bar的宽度占比,优化分组视觉效果
    },
    y: {
      beginAtZero: true,
      title: {
        display: true,
        text: '响应时间'
      }
    }
  },
  plugins: {
    legend: {
      position: 'top',
    },
    title: {
      display: true,
      text: '各系统服务器响应时间'
    }
  }
};

// 初始化图表
new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: data,
  options: options
});

方案二:使用ECharts实现分组展示

ECharts对分组柱状图的支持更直观,同样通过null忽略非对应系统的数据,避免颜色残留:

<div id="main" style="width: 600px;height:400px;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script>
var myChart = echarts.init(document.getElementById('main'));

var option = {
  title: {
    text: '各系统服务器响应时间'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' }
  },
  legend: { data: ['pr1app1', 'pr1app2', 'pr1app3', 'ec1app1'] },
  grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
  xAxis: { type: 'category', data: ['PR1', 'EC1'] },
  yAxis: { type: 'value', name: '响应时间' },
  series: [
    { name: 'pr1app1', type: 'bar', data: [3, null] },
    { name: 'pr1app2', type: 'bar', data: [4, null] },
    { name: 'pr1app3', type: 'bar', data: [7, null] },
    { name: 'ec1app1', type: 'bar', data: [null, 15] }
  ]
};

myChart.setOption(option);
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:32:49