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

如何获取AmCharts堆叠柱状图中被点击的图例分类?

获取AmCharts堆叠柱状图点击的图例分类

我来帮你解决这个问题!在AmCharts的堆叠柱状图中,你点击的柱子所属的**Series(系列)**其实就对应着图例里的分类,所以可以通过以下方式轻松获取:

修改后的点击事件代码

series.columns.template.events.on("hit", function(ev) {
  // 获取当前柱子所属的系列(即图例分类)
  const legendCategory = ev.target.dataItem.component.name;
  // 你原本能获取的年份和数值
  const year = ev.target.dataItem.dataContext.year;
  const value = ev.target.dataItem.value;
  
  console.log(`点击的分类: ${legendCategory}, 年份: ${year}, 数值: ${value}`);
}, this);

原理说明

堆叠柱状图里的每个ColumnSeries实例都对应一个图例项,你在配置series时设置的series.name就是图例上显示的分类名称。当你点击柱子时,ev.target.dataItem.component会指向该柱子所属的Series对象,直接读取它的name属性就能拿到你要的图例分类啦。

举个配置系列的示例,方便你对应理解:

// 示例系列配置
let salesSeries = chart.series.push(new am4charts.ColumnSeries());
salesSeries.dataFields.valueY = "sales";
salesSeries.dataFields.categoryX = "year";
salesSeries.name = "销售额"; // 这就是图例分类名称

let profitSeries = chart.series.push(new am4charts.ColumnSeries());
profitSeries.dataFields.valueY = "profit";
profitSeries.dataFields.categoryX = "year";
profitSeries.name = "利润"; // 另一个图例分类名称

点击对应柱子时,就能分别拿到"销售额"或"利润"这个分类名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:27:32