2017-08-08 50 views
0

您好我是d3js中的新成员,所以我无法在给定的饼图代码中使用mouseover事件...我有一个名为chart的id,所以如何创建有些类是mouseover事件并显示标签?在饼图中使用鼠标悬停并在d3 v3中显示标签js

这里是我使用的绘制饼图代码:

var w = 300; 
var h = 300; 

var dataset = [ 
    {"year":"2017-07-01","value":"5"}, 
    {"year":"2017-07-02","value":"10"}, 
    {"year":"2017-07-03","value":"15"}, 
    {"year":"2017-07-04","value":"20"}, 
    {"year":"2017-07-05","value":"25"}, 
    {"year":"2017-07-06","value":"30"}, 
    {"year":"2017-07-07","value":"35"}, 
    {"year":"2017-07-08","value":"40"}, 
    {"year":"2017-07-09","value":"45"}, 
    {"year":"2017-07-10","value":"50"}, 
    {"year":"2017-07-11","value":"55"}, 
    {"year":"2017-07-12","value":"60"}, 
    {"year":"2017-07-13","value":"65"}, 
    {"year":"2017-07-14","value":"70"} 
]; 

var outerRadius = w/2; 
var innerRadius = 0; 
var arc = d3.svg.arc() 
    .innerRadius(innerRadius) 
    .outerRadius(outerRadius); 

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

var color = d3.scale.category20(); 

var svg = d3.select("#chart") 
    .append("svg") 
    .attr("width", w) 
    .attr("height", h); 

var arcs = svg.selectAll("g.arc") 
    .data(pie(dataset)) 
    .enter() 
    .append("g") 
    .attr("class", "arc") 
    .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")"); 

arcs.append("path") 
    .attr("fill", function(d, i) { 
    return color(i); 
    }) 
    .attr("d", arc); 

arcs.append("text") 
    .attr("transform", function(d) { 
    return "translate(" + arc.centroid(d) + ")"; 
    }) 
    .attr("text-anchor", "middle") 
    .text(function(d) { 
    return d.value; 
    }); 
+0

你想展示什么标签?馅饼中的切片已具有的值?或另一个标签?当用户将鼠标悬停在切片上或用户悬停在整个饼图上时?你看,要得到适当的帮助,你必须准确解释你的想法。 *“我想显示一个标签”*很含糊。 –

+0

我必须在鼠标悬停时显示年值 – kunal

+0

嗯,我只是放弃。祝你好运。 –

回答

2

我使用的工具提示:

var popup=d3.select("body").append("div").attr("class","tooltip").style("opacity",0); 

然后调用提示,添加事件侦听到节点(我猜这会是你的弧线,但我没有做饼图):

nodes.on("mouseover", fade(.1,"over")).on("mouseout",fade(.8,"out")); 

然后把函数放到toolti (在这种情况下或饼图)的节点附近号码:

function fade (opacity, event){ 
return function (d){ 
    if(event === "over"){ 
    popup.transition().duration(100).style("opacity", .9).style("display", "inline-block"); 
    popup.html("Year: " + d.year + "</br> Value: " + d.value) 
    .style("left", (d3.event.pageX + 20) + "px") 
    .style("top", (d3.event.pageY - 20) + "px"); 
    d3.select(this).classed("node-mouseover", true);} 
else if(event==="out"){ 
    popup.transition().duration(100).style("opacity",0); 
    d3.select(this).classed("node-mouseover",false); 

}}}

有这样做的其他方式,但是这似乎是相当受欢迎的this example是相似的。

编辑:请查看bl.ocks.org以获取更多示例。

相关问题