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

D3 v3 环形图数据绑定问题:标签无法读取数据源text字段如何解决?

D3.js环形图标签不显示问题修复方案

核心问题说明

代码里共有4处错误导致text字段无法正常读取、标签不显示:

  • 饼图布局函数未传入原始数据集,绑定数据逻辑错误
  • 饼图布局生成的弧段数据,原始字段存储在d.data属性下,直接读取d.text找不到对应值
  • SVG元素名称拼写错误,使用了不存在的g:path/g:polyline/g:label标签
  • 折线坐标计算时错误对数组做加法运算,导致坐标失效

具体修改点

  1. 修改弧段组的数据绑定逻辑,调用pie函数传入原始数据piedata:
// 修改前
// var arcs = vis.selectAll("g.slice").data(pie).enter().append("svg:g").attr("class", "slice").attr("transform", "translate("  + width/2 + "," + height/2 + ")");
// 修改后
var arcs = vis.selectAll("g.slice").data(pie(piedata)).enter().append("svg:g").attr("class", "slice").attr("transform", "translate("  + width/2 + "," + height/2 + ")");
  1. 修改所有SVG元素名,去掉错误的g:前缀,标签元素改用SVG原生的text标签:
// 路径修改为
arcs.append("path")
// 折线修改为
arcs.append("polyline")
// 标签修改为
arcs.append("text")
  1. 修改标签文本取值逻辑,从d.data中读取原始字段:
// 修改前
// .text(function(d) { return d.text; });
// 修改后
.text(function(d) { return d.data.text; });
  1. 修正折线坐标计算逻辑,避免对数组直接做加法:
.attr('points', function(d) {
  var posA = arc.centroid(d)
  var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
  var posB = outerArc.centroid(d)
  // 给拐点添加径向偏移
  posB[0] += 5 * Math.cos(midangle)
  posB[1] += 5 * Math.sin(midangle)
  var posC = [...posB]
  posC[0] = r * 0.95 * (midangle < Math.PI ? 1 : -1);
  return [posA, posB, posC]
})

修改完成后所有标签即可正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:54:03