-
Notifications
You must be signed in to change notification settings - Fork 4
/
chart.js
117 lines (75 loc) · 2.45 KB
/
chart.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var cheggMap = function() {
"use strict";
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
;
var projection = d3.geo.albersUsa()
.scale(1000);
var colorScale = d3.scale.linear()
.range(['#dddddd', '#1c437b']);
// Helper function to convert array of values into associated map with the State ID # as the key
function mapToID(values) {
var ret = {};
values.forEach(function(d) {
ret[d.id] = d;
});
return ret;
}
function chart(selection) {
selection.each(function(data) {
var dataByID = mapToID(data.data);
var container = d3.select(this);
container
.style('width', width)
.style('height', height);
// Calculate State's color by the extent of the data range
colorScale
.domain(d3.extent(data.data, function(d) { return +d.count }));
projection
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
//--------------------------------------
// Setup common SVG
var wrap = container.selectAll('g.chart-wrap').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'chart-wrap');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
// Chart's layers
gEnter.append('g').attr('class', 'states')
// Account for margin
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//--------------------------------------
var states = g.select('.states').selectAll('path')
.data(topojson.feature(data.map, data.map.objects.states).features);
states.enter().append('path')
.attr('class', 'state')
.attr('d', path)
// Setting fill on update NOT enter so that values can be updated after generating the map
states.transition().duration(1000)
.style('fill', function(d) {
var point = dataByID[d.id],
val = (point && point.count) || 0;
return colorScale(val);
});
});
return chart;
}
chart.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
return chart;
}