简体   繁体   中英

Text not displaying in D3 SVG

I have a problem with appending text to my SVG in d3. What I want to achieve is for text to appear in the red circle as displayed in this image: Circle d3 graph .

For some reason I cannot make the text display and after spending a few hours on this I really don't have any ideas how to solve this... I found a few similar questions on SO but nothing helped me to solve this...

Here are the fragments of the code that I think are crucial to solve this problem:

.on("mousemove", function (d) {
  svg.select("text.text-tooltip1")
    .text(function(d){
    return d3.time.format("%B %d, %Y")(d["data"]);
  })

  svg.select("text.text-tooltip2")
    .text(function(d){
    return "PM emmision:" + d3.round(x(d["ug_mean"]),2);
  })

  svg.select("text.text-tooltip3")
    .text(function(d){
    return "Benzen emmision:" + d3.round(x(d["Precipitationmm"]),2);
  })
})

and

svg.append("circle")
      .attr("class", "exp")
      .attr("cx", 0)
      .attr("cy", 0)
      .attr("r", 130)
      .attr("fill", "#e74747")
      .attr("opacity", "0.8");

svg.append("text")
            .attr("class", "text-tooltip1")
            .attr("dy", "-2em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("class", "text-tooltip2")
            .attr("dy", "1.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("z-index", 100)
            .attr("class", "text-tooltip3")
            .attr("dy", "2.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");

And here is full code on Plunkr: https://plnkr.co/edit/b6PjicI0vOoYSHaDnWS0?p=preview

Thanks a lot for your help!

You need to make two small changes. First, when you append the <text> elements, you are setting class twice. But the second time overwrites the first, so those elements don't have the .text-tooltipN class you expect them to have. In D3 v4, you can use .classed('class-name', true) multiple times without overwriting other classes, but it's easier to just set all at once:

svg.append("text")
  .attr("class", "data text-tooltip1")
  .attr("dy", "-2em")
  .style("text-anchor", "middle");

Second, you don't need two functions inside the mouse event -- notice that you're nesting two cases of function(d){} which means d no longer has the value you want:

.on("mousemove", function (d) {
   svg.select("text.text-tooltip1")
     .text(d3.time.format("%B %d, %Y")(d["data"]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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