Alex
Alex

Reputation: 2402

D3 fill pie chart segment on mouseover

I have a pie chart defined like this:

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

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0.65*radius);

var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")

arc.append("path")
    .attr("d", path)
    .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
    .on('mouseover', function() {console.log('over'); arc.style("fill","red");});

The final line only half works - the console does print 'over', but the segment does not change colour. Is this the wrong approach?

Upvotes: 1

Views: 807

Answers (1)

Xavier Guihot
Xavier Guihot

Reputation: 61666

You should select the current element being hovered with d3.select(this) instead of arc:

// .on('mouseover', function() { arc.style("fill","red"); });
.on('mouseover', function() { d3.select(this).style("fill","red"); });

Here is a demo:

var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var g = svg.append("g").attr("transform", "translate(100,100)")

var data = [
  { value: 4 }, { value: 12 }
];
var colours = ["green", "blue"];
var radius = 25;

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

var path = d3.arc()
    .outerRadius(radius - 10)
    .innerRadius(0.65*radius);

var arc = g.selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc")

arc.append("path")
    .attr("d", path)
    .attr("fill", function(d, i) { return colours[i]; }) //Everything up to here works
    // .on('mouseover', function() { console.log('over'); arc.style("fill","red"); });
    .on('mouseover', function() { console.log('over'); d3.select(this).style("fill","red"); });
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>

Upvotes: 1

Related Questions