官术网_书友最值得收藏!

Making the donut respond to mouse events

If you open the example in your browser, and hover your mouse over one of the donut segments, it pops out a little, and shows a percentage representing the donut segments share. Adding mouse events is very straightforward in D3:

var popupArc = d3.arc() 
.outerRadius(height/2 * 0.65)
.innerRadius(height/2 * 0.3);

arcElements.enter()
.append("path")
.attr("class", "arc")
.style("fill", function (d, i) { return colors(i) })
.merge(arcElements)
.on("mouseover", function(d) {
d3.select(this).attr("d", function(d) {
return popupArc(d);
});
var centerText = pieContainer.selectAll('.center').data([d]);
centerText.enter()
.append('text')
.attr("class","center")
.style("text-anchor","middle")
.merge(centerText)
.text( function(d) { return Math.round(+d.data.count / totalFirms * 100) + "%"});
})
.on("mouseout", function(d) {
d3.select(this).attr("d", function(d) {
return arc(d);
});
// remove the center text
pieContainer.selectAll('.center').text("");
})

In the preceding code, we use the .on("mouseover", function(d) and .on("mouseout", function(d) parameters to add behavior to our donut. The code specified in the provided function is executed whenever that specific event occurs. In the mouseover case we slightly change the radius of the donut segment to simulate the pop-out effect, and add a percentage text element in the center. In the mouseout case, we reset the donut segment to its original size and remove the text.

If you look at the donuts generated in the previous sections, you might notice that we're missing a shadow that was present in the donut shown at the beginning of this chapter. We've added the shadow to make it better looking, but this isn't standard D3 functionality. To add a shadow, we make use of a set of SVG filters that simulate this effect. If you want to add this to your own visualizations, just look at the relevant code in the source file for this example.

Now we've got our final donut, which animates, responds to changes in the menu, and can respond to the mouse, we'll have a look at another standard often seen visualization: the line chart.

主站蜘蛛池模板: 子长县| 永新县| 新巴尔虎右旗| 抚远县| 太仆寺旗| 冷水江市| 荃湾区| 武义县| 灵丘县| 苍溪县| 乐亭县| 中牟县| 当雄县| 会泽县| 新野县| 琼海市| 冀州市| 枞阳县| 安远县| 卫辉市| 景德镇市| 昌邑市| 阿克| 侯马市| 临夏市| 垫江县| 吴川市| 会昌县| 房产| 楚雄市| 新田县| 浦东新区| 建昌县| 吴旗县| 百色市| 南康市| 当雄县| 临沧市| 广水市| 明光市| 西安市|