简体   繁体   English

D3 v4饼图默认文本

[英]D3 v4 pie chart default text

I am quite new in the world of D3. 我在D3世界中是个新手。 Now I would like to create a pie chart based on this example with the exception that the first item in the list would be as a default value on the text displayed in the center. 现在,我想根据此示例创建一个饼图,不同之处在于列表中的第一项将作为显示在中心文本的默认值。 I have tried to chain the functions in different places of the code, but haven't been able to find the correct way to do it. 我试图将函数链接在代码的不同位置,但是还没有找到正确的方法来实现。

Thank you in advance! 先感谢您!

Code also pasted here: 代码也粘贴在这里:

    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);

To get a default value to show up, just append the values during rendering of the chart. 要显示默认值,只需在呈现图表时附加这些值即可。 To update the value mouseover , just select the .text-group and update the values. 要更新mouseover值,只需选择.text-group并更新值。

Check updated codepen 检查更新的代码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM