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

如何设置AmChart旭日图首层级子项文字环形显示,其余径向显示?

在AmChart旭日图中按条件切换标签文字显示类型

要实现按索引/层级条件切换旭日图标签的文字显示类型,核心是利用AmChart的**适配器(adapter)**机制,动态修改标签的textType属性。以下是两种常见场景的实现方案:

方案一:按节点层级区分(第一级子项用环形,后续层级用径向)

如果你的需求是「最内层节点的直接子项(第一个子层级)用circular,第二、第三子层级用radial」,可以通过节点的depth属性判断:

// Create series
var series = container.children.push(am5hierarchy.Sunburst.new(root, {
  singleBranchOnly: true,
  downDepth: 2,
  initialDepth: 4,
  topDepth: 1,
  innerRadius: 100,
  valueField: "value",
  categoryField: "name",
  childDataField: "children"
}));

series.nodes.template.setAll({
  tooltipText: "{category}"
});

series.slices.template.setAll({
  templateField: "nodeSettings"
});

series.labels.template.setAll({
  fontSize: 12,
  text: "{category}",
  inside: true,
  radius: 10,
  fill: am5.color(0xffffff)
});

// 添加textType适配器,按层级切换显示类型
series.labels.template.adapter.add("textType", function(textType, target) {
  const node = target.dataItem;
  // topDepth为1,第一个子层级depth=2用circular;depth=3、4用radial
  if (node.depth === 2) {
    return "circular";
  } else if (node.depth === 3 || node.depth === 4) {
    return "radial";
  }
  return textType;
});

方案二:按同一父节点下的子项索引区分(第一个子项用环形,第二、第三个用径向)

如果需求是「同一父节点下的第一个子元素用circular,第二、第三个子元素用radial」,可以通过节点的index属性判断(索引从0开始):

// Create series
var series = container.children.push(am5hierarchy.Sunburst.new(root, {
  singleBranchOnly: true,
  downDepth: 2,
  initialDepth: 4,
  topDepth: 1,
  innerRadius: 100,
  valueField: "value",
  categoryField: "name",
  childDataField: "children"
}));

series.nodes.template.setAll({
  tooltipText: "{category}"
});

series.slices.template.setAll({
  templateField: "nodeSettings"
});

series.labels.template.setAll({
  fontSize: 12,
  text: "{category}",
  inside: true,
  radius: 10,
  fill: am5.color(0xffffff)
});

// 添加textType适配器,按子项索引切换显示类型
series.labels.template.adapter.add("textType", function(textType, target) {
  const node = target.dataItem;
  // 仅针对非顶层节点(depth>1)
  if (node.depth > 1) {
    const index = node.index;
    if (index === 0) { // 第一个子项
      return "circular";
    } else if (index === 1 || index === 2) { // 第二、第三个子项
      return "radial";
    }
  }
  return textType;
});

说明

适配器会在标签渲染时自动触发,根据节点的属性动态返回对应的textType值。你可以根据实际业务需求调整判断条件(比如修改depth范围、索引值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:23:31