-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bar_Chart_D3_Visualization.html
96 lines (77 loc) · 2.29 KB
/
Bar_Chart_D3_Visualization.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
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
</style>
</head>
<body>
<h1><h1>150 students Favorite subjects</h1></h1>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 30, right: 30, bottom: 100, left: 30}, width = 800 - margin.left - margin.right, height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal().rangeRoundBands([0, width - 300], .38);
var y = d3.scale.linear().range([height, 1]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(15);
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 + ")");
var data = [
{subject: "French", value: 30},
{subject: "English", value: 20},
{subject: "Maths", value: 26},
{subject: "Geography", value: 38},
{subject: "Science", value: 34},
{subject: "UNKNOWN", value: 2}];
var byValue = data.slice(0);
byValue.sort(function(a,b) {
return b.value - a.value;
});
data = byValue;
x.domain(data.map(function(d){return d.subject;}));
y.domain([0, d3.max(data, function(d){return d.value;})]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.style("text-anchor", "end")
.attr("x", 250)
.attr("dy", "4em")
.attr("transform", "rotate(360)" )
.text("Subjects");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -30)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of students");
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.style("fill", "steelblue")
.attr("x", function(d) { return x(d.subject); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); });
</script>
</body>