Gavin
Gavin

Reputation: 1

D3 Donut chart: Display Value on segment hover

Long time lurker 1st time poster. I am trying to display the text value form a CSV file when the relevant segment of pie chart is hovered over. I have the pie chart (thanks to Mike Bostock) and the display when hovering but cant remove it on the mouse out. Any help would be greatly appreciated at this stage.

var width = 960,
    height = 600,
    radius = Math.min(width, height) / 2.5;

var arc = d3.svg.arc()
    .outerRadius(radius + 10)
    .innerRadius(radius - 70);

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

var color = d3.scale.ordinal()
    .range(["#0bd0d2", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);


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


var pieSlice = svg.selectAll("g.slice");

d3.csv("childcare.csv", function(error, data) {

  data.forEach(function(d) {
    d.population = +d.population;
  });

  var arcs = svg.selectAll("g.slice")
      .data(pie(data))
    .enter()
    .append("g")
      .attr("class", "arc")
    arcs.append("path")
        .attr("d", arc)
        .style("fill", function(d) { return color(d.data.place); })

        .on("mouseenter", function(d) {
                //console.log("mousein")
                 arcs.append("text")
                    .attr("transform", arc.centroid(d))
                    .attr("dy", ".5em")
                    .style("text-anchor", "middle")
                    .style("fill", "blue")
                    .attr("class", "on")
                    .text(d.data.place);
        })

        .on("mouseout", function(d) {
                 console.log("mouseout")
        });

});

Upvotes: 0

Views: 4407

Answers (1)

Phuoc Do
Phuoc Do

Reputation: 1344

You can just save your text and remove it on mouseout:

var text;

var arcs = svg.selectAll("g.slice")
    .data(pie(data))
  .enter()
  .append("g")
    .attr("class", "arc")
  arcs.append("path")
      .attr("d", arc)
      .style("fill", function(d) { return color(d.data.place); })

      .on("mouseenter", function(d) {
              //console.log("mousein")
              text = arcs.append("text")
                  .attr("transform", arc.centroid(d))
                  .attr("dy", ".5em")
                  .style("text-anchor", "middle")
                  .style("fill", "blue")
                  .attr("class", "on")
                  .text(d.data.place);
      })

      .on("mouseout", function(d) {
               text.remove();
      });

Upvotes: 3

Related Questions