Javascript D3 v4饼图默认文本

Javascript D3 v4饼图默认文本,javascript,d3.js,Javascript,D3.js,我是D3的新手。现在我想在此基础上创建一个饼图 但列表中的第一项将作为显示在中间的文本的默认值。我曾尝试在代码的不同位置链接函数,但未能找到正确的方法 提前谢谢你 代码也粘贴在这里: var data = [ {name: "USA", value: 40}, {name: "UK", value: 20}, {name: "Canada", value: 30}, {name: "Maxico", value: 10}, ]; var text = ""; var wid

我是D3的新手。现在我想在此基础上创建一个饼图 但列表中的第一项将作为显示在中间的文本的默认值。我曾尝试在代码的不同位置链接函数,但未能找到正确的方法

提前谢谢你

代码也粘贴在这里:

    var data = [
{name: "USA", value: 40},
  {name: "UK", value: 20},
  {name: "Canada", value: 30},
  {name: "Maxico", value: 10},
];
var text = "";

var width = 260;
var height = 260;
var thickness = 40;
var duration = 750;

var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory10);

var svg = d3.select("#chart")
.append('svg')
.attr('class', 'pie')
.attr('width', width)
.attr('height', height);

var g = svg.append('g')
.attr('transform', 'translate(' + (width/2) + ',' + (height/2) + ')');

var arc = d3.arc()
.innerRadius(radius - thickness)
.outerRadius(radius);

var pie = d3.pie()
.value(function(d) { return d.value; })
.sort(null);

var path = g.selectAll('path')
.data(pie(data))
.enter()
.append("g")
.on("mouseover", function(d) {
      let g = d3.select(this)
        .style("cursor", "pointer")
        .style("fill", "black")
        .append("g")
        .attr("class", "text-group");

      g.append("text")
        .attr("class", "name-text")
        .text(`${d.data.name}`)
        .attr('text-anchor', 'middle')
        .attr('dy', '-1.2em');

      g.append("text")
        .attr("class", "value-text")
        .text(`${d.data.value}`)
        .attr('text-anchor', 'middle')
        .attr('dy', '.6em');
    })
  .on("mouseout", function(d) {
      d3.select(this)
        .style("cursor", "none")  
        .style("fill", color(this._current))
        .select(".text-group").remove();
    })
  .append('path')
  .attr('d', arc)
  .attr('fill', (d,i) => color(i))
  .on("mouseover", function(d) {
      d3.select(this)     
        .style("cursor", "pointer")
        .style("fill", "black");
    })
  .on("mouseout", function(d) {
      d3.select(this)
        .style("cursor", "none")  
        .style("fill", color(this._current));
    })
  .each(function(d, i) { this._current = i; });


g.append('text')
  .attr('text-anchor', 'middle')
  .attr('dy', '.35em')
  .text(text);

要获得显示的默认值,只需在图表呈现期间附加这些值。要更新鼠标上方的值,只需选择
.text组
,然后更新值


选中“已更新”

生成代码的工作片段。这样会更快更容易调试。像这样吗?枪手做对了。谢谢将其作为答案发布可能会有所帮助。