円グラフにmouseover
バインドされているデータだけでなく、円グラフに多くのテキストを表示する方法を見つけようとしています。以下は私の関数型コードです
function Pie(value,names){
svg.selectAll("g.arc").remove()
var outerRadius = 100;
var innerRadius = 0;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.layout.pie();
var color = d3.scale.category10();
var arcs = svg.selectAll("g.arc")
.data(pie(value))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(950,80)");
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.on("mouseover",function(d,i) {
arcs.append("text")
.attr("dy", ".5em")
.style("text-anchor", "middle")
.style("fill", function(d,i){return "black";})
.text(d.data)
})
.on("mouseout", function(d) {
arcs.select("text").remove();
});}
names
配列は同じ長さを有するvalue
パイに渡される配列。上記を置き換えることで、このようなことがうまくいくことを本当に望んでいましたmouseover
。
.on("mouseover",function(d,i) {
arcs.append("text")
.attr("dy", ".5em")
.style("text-anchor", "middle")
.style("fill", function(d,i){return "black";})
.text(function(d,i){return (d.data +" " + names[i]);)
})
しかし、それが行う唯一のことは、values
配列のすべての要素を積み重ねて表示し、配列の最後の要素を表示することnames
です。i
この場合、それが常に最後のインデックスであるように思われます。どうすればいいですか?別の方法で必要なテキストを表示できますか?前もって感謝します。
まず、変数arcs
は、円のすべての円弧を表すデータバインドされたd3選択です。したがって、を呼び出すarcs.append
ことtext
により、円グラフの各部分に要素を追加します。text
マウスオーバーした内容に基づいて1つの要素のみを追加することを意味していると思いますので、次のように書き直してください。
svg.append('text')
...
次に、この式では次のようになります。
.text(function(d,i){return (d.data +" " + names[i]);)
d
とi
にマウスオーバー機能すでにビーイングは、マウスオーバー円スライスのデータとインデックスを表します。これを別の関数でラップする理由はなく、書き直す必要があります。
.text(d.data +" " + names[i]);
完全な例を次に示します。
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category10();
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var data = [{
value: Math.random(),
}, {
value: Math.random(),
}, {
value: Math.random(),
}, {
value: Math.random(),
}, {
value: Math.random(),
}]
var names = ["A","B","C","D","E"];
var arcs = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
arcs.append("path")
.attr("d", arc)
.style("fill", function(d,i) {
return color(i);
})
.on("mouseover", function(d, i) {
console.log(d);
svg.append("text")
.attr("dy", ".5em")
.style("text-anchor", "middle")
.style("font-size", 45)
.attr("class","label")
.style("fill", function(d,i){return "black";})
.text(names[i]);
})
.on("mouseout", function(d) {
svg.select(".label").remove();
});
</script>
</body>
</html>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加