d3条形图将文本追加到条形图 [英] d3 Bar Chart append text to bar
本文介绍了d3条形图将文本追加到条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经按照教程制作了斯科特·默里(Scott Murray)从alignedleft制作的条形图.我的数据集出现问题,并将数据集作为文本添加到了条形图.
I've followed the tutorial to make a bar chart from Scott Murray from alignedleft. I'm having problem with my dataset and adding the dataset to a bar as text.
下图:1条形图:来自教程,2条形图:我要如何显示文本.
The image below: 1 bar chart: from the tutorial , 2nd bar chart: how I want to display the text.
到目前为止,这是我的代码:
Here's my code so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tutorial d3 bar chart!</title>
<script type="text/javascript" src="d3/d3.v3.js"></script>
</head>
<body>
<script type="text/javascript">
//Width and height
var w = 500;
var h = 100;
var i = 0;
var barPadding = 1;
var dataset = [
{key:"Department1", value:6234490},
{key:"Department 2", value:9700},
{key:"Department 3", value:2954},
];
//Width and height
var w = 500;
var h = 100;
var barPadding = 1;
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - (d * 4);
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return d * 4;
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
});
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
for(int i = 0; i < dataset.length; i++){
return d[i].key;
}
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return i * (w / dataset.length) + (w / dataset.length - barPadding) / 2;
})
.attr("y", function(d) {
return h - (d * 4) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
</script>
</body>
</html>
我尝试在此部分添加文本:
I've tried to add the text in this part:
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
for(int i = 0; i < dataset.length; i++){
return d[i].key;
}
})
但这只是给我这个错误:
But that just gives me this error:
我希望你们能帮助我.
推荐答案
尝试将int更改为var,javascript中不存在int.
Try changing int to var, int doesn't exist in javascript.
这篇关于d3条形图将文本追加到条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文