你们有没有让我知道为什么传奇在我的代码中没有正确显示。我在这里粘贴了块的链接:https://bl.ocks.org/abrahamdu/2038544bffad6b5b25760b42ef519a7e
答案 0 :(得分:0)
问题是矩形和文本的legend.append("text")
.attr("x", width + 10)
//etc...
legend.append("rect")
.attr("x", width - 10)
//etc...
位置:
<g>
您可能认为它将它们放在SVG的右边框旁边,但它并没有:父width/2
元素被转换为<g>
。因此,这些传说远远超出SVG限制。
解决方案:不要翻译那些.attr("transform", function(d,i){ return "translate(0," + i * 30 + ")";});
//look at the zero here ----------------------------^
元素......
radius
...并使用legend.append("text")
.attr("x", radius + 30)
设置矩形和文本位置:
var margin = {
top: 30,
right: 30,
bottom: 50,
left: 30
};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(["#0095D9", "#9C9536", "#F5E837"]);
var data = [{
"type": "Sky",
"pop": 0.75
}, {
"type": "Shady side of pyramid",
"pop": 0.07
}, {
"type": "Sunny side of pyramid",
"pop": 0.18
}];
var g = d3.select("svg")
.append("g")
.attr("transform", "translate(" + width / 1.8 + "," + height / 1.6 + ")");
var pie = d3.pie().sort(null)
.value(function(d) {
return d.pop;
})(data);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0)
.startAngle(function(d) {
return d.startAngle + Math.PI * 1.2;
})
.endAngle(function(d) {
return d.endAngle + Math.PI * 1.2;
});;
var label = d3.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 10);
var pyramid = g.selectAll(".arc")
.data(pie)
.enter()
.append("g")
.attr("class", "arc");
pyramid.append("path")
.attr("d", arc)
.style("fill", function(d) {
return color(d.data.type);
});
var legend = pyramid.append("g")
.attr("class", "legend")
.attr("font-family", "sans-serif")
.attr("font-size", 20)
.attr("text-anchor", "start")
.selectAll("g")
.data(pie)
.enter().append("g")
.attr("transform", function(d, i) {
return "translate(0," + i * 30 + ")";
});
legend.append("text")
.attr("x", radius + 30)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) {
return d.data.type;
});
legend.append("rect")
.attr("x", radius + 10)
.attr("width", 19)
.attr("height", 19)
.attr("fill", function(d) {
return color(d.data.type);
});
以下是演示:
body {
background-color: lightgrey;
}
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="960" height="500"></svg>
&#13;
var charSet = 'A'..'Z'
for (value in charSet) {
println("$value")
}
&#13;