我对 d3.js 编程很陌生,我想知道是否有人可以帮助我解决以下问题:
我修改了我在网上找到的一个圆环图。我修改成了响应式 同时仍然保持纵横比为 1 对于圆形圆环图。我想知道最好的方法是什么 在其上方或下方放置标题 .我尝试了各种方法,但我无法创建一种始终有效的方法。
此处简化了 JSFiddle:
JSFiddle
代码也附在这里:
var width = 400;
var height = 400;
var x = {
value: 80.43,
color1: "#007EA7",
color2: "#d9d9d9"
};
var margin = {
left: 10,
top: 10,
right: 10,
bottom: 10
};
width = Math.min(width - margin.left - margin.right,
height - margin.top - margin.bottom);
height = width * 1; // Should be a perfect circle.
svg = d3.select("body")
.append("div")
.classed("svg-container", true)
.append("svg")
.attr("preserveAspectRatio", "xMidYMin meet")
.attr("viewBox", "0 0 " + (width) + " " + (height))
.classed("svg-content-responsive", true);
// Below is code to create the actual donut chart. It used the width and height attributes calculated above.
var outerRadius = Math.min(width, height) / 2,
innerRadius = (outerRadius / 5) * 4;
τ = 2 * Math.PI;
fontSize = (Math.min(width, height) / 5);
arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.startAngle(0);
var background = svg.append("path")
.datum({
endAngle: τ
})
.style("fill", x.color2)
.attr("d", arc)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var text = svg.append("text")
.text(Math.round(x.value * 10) / 10 + '%')
.attr("text-anchor", "middle")
.style("font-size", fontSize + 'px')
.attr("dy", height / 2 + fontSize / 2.5)
.attr("dx", width / 2);
foreground = svg.append("path")
.datum({
endAngle: x.value / 100 * τ
})
.style("fill", x.color1)
.attr("d", arc)
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
.svg-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.svg-content-responsive {
width: 100%;
height: 100%;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
非常感谢任何可能对我有帮助的评论、建议、引用或代码片段。
谢谢,
弗洛里安
最佳答案
添加类似 this 的内容有什么问题吗? :
var title = svg.append("text")
.text('This is the title')
.attr("text-anchor", "middle")
.style("font-size", '12px')
.attr("dy", 10)
.attr("dx", width / 2);
一模一样的
text
?PS:添加失败的方法将有助于人们回答问题
关于d3.js 标题上方具有固定纵横比的响应式图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072959/