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

amCharts 5 印度地图多边形与图例颜色不匹配问题求助

amCharts 5 印度地图多边形与图例颜色不匹配问题求助

我仔细瞅了你的代码,发现问题根源其实挺明确的,咱们一步步给你捋顺:

核心问题分析

你现在的代码里同时做了两件冲突的事:

  1. 手动给每个州的data对象分配了自定义颜色(放在polygonSettings.fill里)
  2. 又开启了heatRules热力规则,这玩意儿会强制根据purchases_contribution的值自动计算填充色,直接覆盖你手动设置的颜色——这就是为啥地图全是灰色(或者热力规则计算出来的统一色调),而图例能拿到正确颜色的原因:图例是你手动从数据里取的,没受热力规则影响。

另外还有个小细节:你配置了fillField: "fill",但把颜色放在了polygonSettings.fill字段里,字段名不匹配,系列根本读不到你设置的颜色。

具体修改方案

1. 移除热力规则(关键!)

直接删掉这段代码,因为你是按排名手动分配颜色,不需要自动热力计算:

// 删掉这整段
polygonSeries.set("heatRules", [{ target: polygonSeries.mapPolygons.template, dataField: "purchases_contribution", min: am5.color(0x000000), max: am5.color(0xFFFFFF), key: "fill" }]);

2. 把颜色直接放到fill字段里

修改数据处理的循环,把颜色直接赋值给fill字段,和你配置的fillField对应上:

data.forEach((item, index) => {
  // 原来的polygonSettings.fill改成直接写fill字段
  item.fill = am5.color(colorPalette[index] || 0xe0e0e0);
});

3. 确保系列配置正确读取fill字段

在创建MapPolygonSeries的时候,明确加上fillField: "fill"(你之前的series配置里漏了这个):

const polygonSeries = chart.series.push(am5map.MapPolygonSeries.new(root, {
  geoJSON: am5geodata_indiaLow,
  valueField: "purchases_contribution",
  nameField: "name",
  fillField: "fill", // 必须加上,告诉系列用数据里的fill字段作为填充色
  calculateAggregates: true
}));

4. 调整适配器逻辑(可选)

如果你想给没有数据的州保留灰色默认色,可以修改适配器,优先读取数据里的fill:

polygonSeries.mapPolygons.template.adapters.add("fill", (fill, target) => {
  const dataItem = target.dataItem;
  // 优先用数据里的自定义颜色,没有的话用灰色
  return dataItem && dataItem.dataContext.fill ? dataItem.dataContext.fill : am5.color(0xe0e0e0);
});

5. 优化图例数据生成

直接从数据上下文取颜色,不用绕到polygon对象,更可靠:

polygonSeries.events.on("datavalidated", function () {
  console.log("[am5] Data validated. Populating legend.");
  const legendData = polygonSeries.dataItems
    .filter(dataItem => dataItem.get("value") !== undefined)
    .map(dataItem => {
      const dataContext = dataItem.dataContext;
      return {
        name: `${ dataContext.name } - ${ dataContext.purchases_contribution }%`,
        fill: dataContext.fill || am5.color(0x999999)
      };
    });
  console.log("[am5] Filtered legend data:", legendData);
  legend.data.setAll(legendData);
});

这样改完之后,地图的多边形颜色就会和图例完全对应上了——现在系列会直接读取你手动分配的fill字段,没有热力规则来捣乱啦~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 03:10:49