調整數字位置於 bar 上方並且改顏色,避免 bar 的高度不足擋到數字。調整 bar 寬度避免擋到隔壁的數字
-
-
Save ctiml/f04e3eafabe0a31cfe5f to your computer and use it in GitHub Desktop.
03-Bar Chart III
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name | value | |
---|---|---|
A | .08167 | |
B | .01492 | |
C | .02782 | |
D | .04253 | |
E | .12702 | |
F | .02288 | |
G | .02015 | |
H | .06094 | |
I | .06966 | |
J | .00153 | |
K | .00772 | |
L | .04025 | |
M | .02406 | |
N | .06749 | |
O | .07507 | |
P | .01929 | |
Q | .00095 | |
R | .05987 | |
S | .06327 | |
T | .09056 | |
U | .02758 | |
V | .00978 | |
W | .02360 | |
X | .00150 | |
Y | .01974 | |
Z | .00074 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.chart rect { | |
fill: steelblue; | |
} | |
.chart text { | |
fill: black; | |
font: 10px sans-serif; | |
text-anchor: middle; | |
} | |
</style> | |
<svg class="chart"></svg> | |
<script src="//d3js.org/d3.v3.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var y = d3.scale.linear() | |
.range([height - 10, 0]); | |
var chart = d3.select(".chart") | |
.attr("width", width) | |
.attr("height", height); | |
d3.tsv("data.tsv", type, function(error, data) { | |
y.domain([0, d3.max(data, function(d) { return d.value; })]); | |
var barWidth = width / data.length; | |
var bar = chart.selectAll("g") | |
.data(data) | |
.enter().append("g") | |
.attr("transform", function(d, i) { return "translate(" + i * barWidth + ",0)"; }); | |
bar.append("rect") | |
.attr("x", 5) | |
.attr("y", function(d) { return y(d.value) + 12; }) | |
.attr("height", function(d) { return height - y(d.value); }) | |
.attr("width", barWidth - 10); | |
bar.append("text") | |
.attr("x", barWidth / 2) | |
.attr("y", function(d) { return y(d.value) + 3; }) | |
.attr("dy", ".75em") | |
.text(function(d) { return d.value; }); | |
}); | |
function type(d) { | |
d.value = +d.value; // coerce to number | |
return d; | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment