如何将两个元素(循环和文本)添加到SVG g元素和D3js中?

时间:2021-02-21 19:54:25

I like to add a circle and a text element to a SVG chart. With following code only the circle is added.

我喜欢在SVG图表中添加一个圆圈和一个文本元素。下面的代码只添加了这个圆。

// Draw chart
let entry = d3.select( ".chart" ).selectAll("g")
    .data(data)
    .enter().append("g")
      .attr("transform", (date, i) => "translate("+ (width - x(date.Seconds - data[0].Seconds)) +", "+ (padding+i*y) + ")")
      .classed("doping", (d) => d.Doping !== "" );

entry.append("circle")
      .attr("cx", 0)
      .attr("cy", 0)
      .attr("r", y*0.4)
      .attr("name ", (d) => d.Name )
      .attr("country", (d) => d.Nationality )
      .attr("year", (d) => d.Year )
      .attr("time", (d) => d.Time )
      .attr("allegation", (d) => d.Doping );

entry.append("text")
      .text((d) => d.Name)
      .attr("x", y*2)
      .attr("y", 0)
      .classed("text", true);

I can append only the text element, if I omit the circle. But not both.

如果省略了圆,我只可以追加文本元素。但不能两者兼得。

The codepen: http://codepen.io/lafisrap/pen/zwwqzw

codepen:http://codepen.io/lafisrap/pen/zwwqzw

How can I do that?

我该怎么做呢?

1 个解决方案

#1


1  

It's because you are trying to set non existent attributes to the circle.

因为你试图将不存在的属性设置成圆圈。

Remove these lines and it will work

删除这些行,它就会起作用。

  .attr("name ", (d) => d.Name )
  .attr("country", (d) => d.Nationality )
  .attr("year", (d) => d.Year )
  .attr("time", (d) => d.Time ) 

codepen

codepen

#1


1  

It's because you are trying to set non existent attributes to the circle.

因为你试图将不存在的属性设置成圆圈。

Remove these lines and it will work

删除这些行,它就会起作用。

  .attr("name ", (d) => d.Name )
  .attr("country", (d) => d.Nationality )
  .attr("year", (d) => d.Year )
  .attr("time", (d) => d.Time ) 

codepen

codepen