我对d3.js很新,我尝试创建一个非常简单的进度here。
代码是:
var data = [2000, 200]; // here are the data values; v1 = total, v2 = current value
var chart = d3.select("#container").append("svg") // creating the svg object inside the
.attr("class", "chart")
.attr("width", 400) // bar has a fixed width
.attr("height", 30 * data.length);
var x = d3.scale.linear() // takes the fixed width and creates the percentage from the data
.domain([0, d3.max(data)])
.range([0, 400]);
chart.selectAll("rect") // this is what actually creates the bars
.data(data)
.enter().append("rect")
.attr("width", x)
.attr("height", 10)
.attr("rx", 5) // rounded corners
.attr("ry", 5);
var text = [0,200,2000]
chart.selectAll("text") // adding the text labels to the bar
.data(text)
.enter().append("text")
.attr("x", x)
.attr("y", 20) // y position of the text inside bar
.attr("dx", -3) // padding-right
.attr("dy", ".35em") // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.text(String);
渲染图表。这里有几个问题:
0
,但它不可见。 感谢您的帮助!
答案 0 :(得分:1)
要显示矩形上方的任何文字,您必须将其向下移动一点。
关于文本,您可以设置不同的锚点......
.attr("y", function(_, i) {
return i === 1 ? 36 : 10;
})
...使用索引的不同垂直位置:
var data = [2000, 200]; // here are the data values; v1 = total, v2 = current value
var chart = d3.select("#container").append("svg") // creating the svg object inside the
.attr("class", "chart")
.attr("width", 400) // bar has a fixed width
.attr("height", 30 * data.length);
var x = d3.scale.linear() // takes the fixed width and creates the percentage from the data
.domain([0, d3.max(data)])
.range([0, 400]);
chart.selectAll("rect") // this is what actually creates the bars
.data(data)
.enter()
.append("rect")
.attr("y", 18)
.attr("width", x)
.attr("height", 10)
.attr("rx", 5) // rounded corners
.attr("ry", 5);
var text = [0, 200, 2000]
chart.selectAll("text") // adding the text labels to the bar
.data(text)
.enter()
.append("text")
.attr("x", x)
.attr("y", function(_, i) {
return i === 1 ? 36 : 10;
}) // y position of the text inside bar // padding-right
.attr("dy", ".35em") // vertical-align: middle
.attr("text-anchor", function(_, i) {
return ["start", "middle", "end"][i]
}) // text-align: right
.text(String);
以下是更新后的代码:
.chart rect:first-of-type {
color: #fff;
stroke: #3994b6;
fill: white;
}
#container {
padding: 30px
}
text:first-of-type {
fill: #3994b6;
font-family: sans-serif;
font-size: 12px;
}
.chart rect:nth-of-type(2) {
color: #fff;
stroke: transparent;
fill: #3994b6;
}
text:nth-of-type(2) {
fill: #a8d4e4;
font-family: sans-serif;
font-size: 12px;
}
.chart rect:nth-of-type(3) {
color: #fff;
stroke: transparent;
fill: #3994b6;
}
text:nth-of-type(3) {
fill: #a8d4e4;
font-family: sans-serif;
font-size: 12px;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="container"></div>
{{1}}