2

possible duplicates: D3 text on mouseover

D3 donut chart text centering

but unsure what is happening in respect to my problem and quite stuck.

Im building a data visualization with many layouts. I am currently trying to make a piechart with text centered in the middle and whenever someone mouse overs the arcs, it displays the text of it in the center.

function GUP_PieRender() {

var svg = d3.select(targetDOMelement).append("svg")
   .attr("width", width)
   .attr("height", height)
 .append("g")
   .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var g = svg.selectAll(".arc")
  .data(pie(dataset))
.enter().append("g")
  .attr("class", "arc")
  .on("mouseover", function(d) { d3.select("text").text(d.data.ResearchArea)}); //Problem area

g.append("path")
  .attr("d", arc)
  .style("fill", function(d) { return color(d.data.ResearchArea); });

g.append("text")
  .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
  .attr("dy", ".35em")
  .style("text-anchor", "middle"); 
}

What it is doing instead is displaying the text in another D3 barchart layout that has text. So I must be calling the mouseover event too early and appending it to the last text element in that?

Can I get a remedy?

Thanks.

Stu
  • 67
  • 6

1 Answers1

1

The problem here (inside your "mouseover" handler) is simply this:

d3.select("text")

When you do this, D3 selects the first text element it finds in that page. You don't want that, obviously.

Therefore, just do:

g.select("text")

That way, you only select text elements inside your g selection.

Alternatively, you can also do:

d3.select(this).select("text")

Since this in this context is the group element.

Here is a demo (I'm trying to imitate your code):

var data = ["foo", "bar", "baz"];
data.forEach(function(d) {
  render(d);
})

function render(data) {
  var svg = d3.select("body")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);

  var g = svg.selectAll(null)
    .data([data])
    .enter()
    .append("g")
    .on("mouseover", function(d) {
      g.select("text").text(String)
    })
    .on("mouseout", function(d) {
      g.select("text").text(null)
    })

  g.append("circle")
    .attr("cx", 50)
    .attr("cy", 50)
    .attr("r", 20);

  g.append("text")
    .attr("x", 25)
    .attr("y", 20);
}
svg {
  background-color: tan;
  border: 1px solid darkgray;
  margin-right: 10px;
}

circle {
  fill: teal;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171