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

如何实现Highcharts饼图运行时隐藏指定图例项且无空白间隙

要避免CSS隐藏图例带来的空白间隙,直接使用Highcharts原生的showInLegend属性控制单个数据项是否在图例展示即可,该方案只会隐藏对应图例项,不会影响饼图本身的渲染、占比计算和数据标签显示,同时图例区域会自动重新排版,不会出现空白。

实现方案

1. 初始化时直接隐藏指定项

在对应需要隐藏的series.data数据项中添加showInLegend: false配置即可,如果需要保留原有颜色索引,可手动为每个数据项指定colorIndex属性避免隐藏后颜色错位。
示例代码:

Highcharts.chart('container', {
  chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
  },
  title: {
    text: '2018年1月浏览器市场份额'
  },
  tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
  },
  accessibility: {
    point: {
      valueSuffix: '%'
    }
  },
  plotOptions: {
    pie: {
      allowPointSelect: true,
      cursor: 'pointer',
      dataLabels: {
        enabled: true,
        format: '<b>{point.name}</b>: {point.percentage:.1f} %'
      }
    }
  },
  series: [{
    name: '品牌',
    colorByPoint: true,
    data: [{
      name: 'Chrome',
      y: 61.41,
      sliced: true,
      selected: true,
      showInLegend: false, // 隐藏第一个图例项
      colorIndex: 0 // 固定颜色索引,避免后续颜色错位
    }, {
      name: 'Internet Explorer',
      y: 11.84,
      colorIndex: 1
    }, {
      name: 'Firefox',
      y: 10.85,
      colorIndex: 2
    }, {
      name: 'Edge',
      y: 4.67,
      colorIndex: 3
    }, {
      name: 'Safari',
      y: 4.18,
      colorIndex: 4
    }, {
      name: '搜狗浏览器',
      y: 1.64,
      colorIndex: 5
    }, {
      name: 'Opera',
      y: 1.6,
      colorIndex: 6
    }, {
      name: 'QQ浏览器',
      y: 1.2,
      colorIndex: 7
    }, {
      name: '其他',
      y: 2.61,
      showInLegend: false, // 隐藏Other项的图例
      colorIndex: 8
    }]
  }]
});

2. 运行时动态隐藏指定项

如果需要在图表渲染完成后动态隐藏/显示图例项,调用对应数据点的update方法修改showInLegend属性即可,图表会自动重排图例:

// 获取图表实例
const chart = Highcharts.charts[0];

// 按名称查找Other项并隐藏图例
const otherPoint = chart.series[0].points.find(p => p.name === '其他');
otherPoint.update({ showInLegend: false });

// 按索引隐藏第一个项的图例
const firstPoint = chart.series[0].points[0];
firstPoint.update({ showInLegend: false });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:57:02