forked from sdqali/d3-dojo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-barchart3.html
125 lines (110 loc) · 2.6 KB
/
03-barchart3.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>
Barchart with Axes
</title>
<script type='text/javascript' src='/d3/d3.v2.min.js'>
</script>
<style type='text/css'>
#barchart {
margin-left: 50px;
float: left;
}
.chart {
margin-left: 50px;
float: left;
}
.chart rect {
stroke: white;
fill: SteelBlue;
}
.axis path,
.axis line {
stroke: black;
fill: none;
shape-rendering: crispEdges;
}
.axis text {
font-size: 11px;
}
</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) - xScale(0);
})
.attr("x", function(d) {
return margins.left;
})
.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");
//Add x axis
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(20)
.orient("bottom");
chart.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (height - margins.bottom) + ")")
.call(xAxis);
// Add y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.ticks(data.length)
.orient("left");
chart.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + margins.left +", 0)")
.call(yAxis);
});
</script>
</body>
</html>