1
我想將值標籤添加爲條形圖中每個條上方的黑色文本。代碼靈感來自http://bl.ocks.org/mbostock/3885304。我已經在數據文件的下面發佈了它。我試圖在index.html
的末尾添加代碼段來創建值標籤,但我沒有將任何文本添加到圖中。將值標籤添加到D3條形圖
的index.html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
shape-rendering: crispEdges;
}
.bar text {
//fill: black;
font: 11x sans-serif;
stroke: black;
}
.bar:hover {
fill: brown;
}
.axis {
font: 11x sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
display: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 90, left: 55},
width = 400 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(10, "%");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", type, function(error, data) {
x.domain(data.map(function(d) { return d.group; }));
//y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
y.domain([0, 1]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
//.attr("dx", "-.8em")
//.attr("dy", ".15em")
.attr("dx", "-.6em")
.attr("dy", ".35em")
.attr("transform", function(d) {
return "rotate(-45)"
});
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.group); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
// A formatter for counts.
var formatCount = d3.format(",.0f");
// Add value labels
valueLabels = bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", function(d) { return x(d.group); })
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(y(d.frequency)); });
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
</script>
data.tsv
group frequency
1-9 weeks .036197
10-12 weeks .0457085
13 weeks .0714285
14 weeks .846666
你有嗎? een [本教程](http://bost.ocks.org/mike/bar/2/)? –