forked from sdqali/d3-dojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-barchart2.html
79 lines (72 loc) · 1.73 KB
/
02-barchart2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>
Barchart with Scales
</title>
<script type='text/javascript' src='/d3/d3.v2.min.js'>
</script>
<style type='text/css'>
.chart rect {
stroke: white;
fill: SteelBlue;
}
</style>
</head>
<body>
<div id="barchart">
</div>
<script type='text/javascript'>
d3.csv ("accident_deaths.csv", function (data) {
var width = 1000;
var height = 500;
var margins = {
left: 50,
top: 50,
right: 50,
bottom: 50
};
var chart = d3.select("#barchart").append("svg")
.attr ("class", "chart")
.attr ("width", width)
.attr ("height", height);
var xScale = d3.scale.linear ()
.domain ([0, d3.max (data, function (d) {return d.deaths;})])
.range ([margins.left, width - margins.right]);
var yScale = d3.scale.ordinal ()
.domain (data.map (function (d) {return d.year;}))
.rangeBands ([margins.top, height - margins.bottom]);
// Add rectangles
chart.selectAll ("rect")
.data (data)
.enter ()
.append ("rect")
.attr ("width", function (d) {
return xScale (d.deaths);
})
.attr ("height", yScale.rangeBand ())
.attr ("y", function (d, i) {
return yScale (d.year);
});
// Add text showing number of deaths
chart.selectAll ("text")
.data (data)
.enter ()
.append ("text")
.text (function (d) {
return String (d.deaths);
})
.attr ("x", function (d) {
return xScale (d.deaths);
})
.attr ("y", function (d, i) {
return yScale (d.year) + yScale.rangeBand () / 2;
})
.attr("dy", ".35em")
.attr("dx", "-5")
.attr ("text-anchor", "end");
});
</script>
</body>
</html>