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

如何在Chart.js堆叠柱状图中仅为指定数据集显示图例?

可以实现,有两种常用方案:

方案1:数据集内直接配置(最简单)

不需要修改全局图例的显示规则,只需要给不想显示图例的数据集添加skipLegend: true属性即可,示例如下:

const chartConfig = {
  type: 'bar',
  data: {
    labels: ['1月', '2月', '3月'],
    datasets: [
      // 需要显示图例的数据集1
      {
        label: '销量',
        data: [120, 190, 300],
        backgroundColor: '#f87171'
      },
      // 需要显示图例的数据集2
      {
        label: '利润',
        data: [30, 45, 70],
        backgroundColor: '#60a5fa'
      },
      // 不需要显示图例的数据集3
      {
        label: '损耗',
        data: [5, 8, 12],
        backgroundColor: '#34d399',
        skipLegend: true // 新增此行,该数据集不会生成对应图例项
      }
    ]
  },
  options: {
    scales: {
      x: { stacked: true },
      y: { stacked: true }
    }
  }
}

方案2:图例过滤器回调(适合复杂筛选逻辑)

如果有动态筛选、多条件判断等需求,可以在图例配置中新增filter回调函数,返回true的图例项会保留,返回false则会隐藏:

options: {
  // Chart.js 3.x及以上版本配置路径
  plugins: {
    legend: {
      filter: (legendItem, chartData) => {
        // 示例:仅展示索引为0、1的数据集图例,隐藏索引为2的数据集
        return legendItem.datasetIndex < 2
        // 也可以按数据集名称过滤,比如隐藏label为“损耗”的数据集图例
        // return legendItem.text !== '损耗'
      }
    }
  }
  // Chart.js 2.x版本配置路径
  // legend: {
  //   filter: function(legendItem, chartData) {
  //     return legendItem.datasetIndex < 2
  //   }
  // }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:24:07