-
Notifications
You must be signed in to change notification settings - Fork 8
/
d3graphs.js
96 lines (83 loc) · 3.06 KB
/
d3graphs.js
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
// ======= ======= ======= initHorizontalChart ======= ======= =======
function initHorizontalChart(schoolName, schoolDataArray) {
console.log("initHorizontalChart");
// ======= chart formatting =======
var chartPadding = {top: 5, right: 20, bottom: 80, left: 50},
chartW = 280 - chartPadding.left - chartPadding.right, // outer width of chart
chartH = 260 - chartPadding.top - chartPadding.bottom; // outer height of chart
var dataH = d3.max(schoolDataArray, function(d) {
return d.value;
});
var dataMax = d3.max(schoolDataArray, function(d) {
return d.value;
})
// ======= scale mapping (data to display) =======
var xScale = d3.scale.ordinal()
.rangeRoundBands([0, chartW], .1)
.domain(schoolDataArray.map(function(d) {
return d.key;;
}));
var yScale = d3.scale.linear()
.domain([0, d3.max(schoolDataArray, function(d) {
return +d.value;
})])
.range([chartH, 0]);
// ======= scale label formating =======
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
// ======= build svg objects =======
$("#chartData").empty();
var svg = d3.select("#chartData").append("svg")
.attr("width", chartW + (chartPadding.left + chartPadding.right))
.attr("height", chartH + (chartPadding.top + chartPadding.bottom))
.append("g")
.attr("transform", "translate(" + chartPadding.left + "," + chartPadding.top + ")");
// ======= X scale =======
svg.append("g")
.data(schoolDataArray)
.attr("class", "x axis")
.attr("transform", "translate(0, " + chartH + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)" );
// ======= Y scale =======
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("y", -30)
.attr("x", 30)
.attr("dy", ".71em")
.style("font-size", "10px")
.style("text-anchor", "start");
// ======= rects for bar graph =======
svg.selectAll(".bar")
.data(schoolDataArray)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return xScale(d.key); })
.attr("width", xScale.rangeBand() - 20)
.attr("y", function(d) { return yScale(d.value); })
.attr("height", function(d) {
return chartH - yScale(d.value);
})
.style({'fill': function(d, i) {
whichColor = 'rebeccapurple';
return whichColor;
}})
.style("font-size", "10px");
// ======= stringToInt =======
function stringToInt(d) {
// console.log("stringToInt");
d.value = +d.value;
return d;
}
}