2017-08-08 56 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以獲取更多示例。

相關問題