-
Notifications
You must be signed in to change notification settings - Fork 40
/
multiple_lines_voronoi.html
379 lines (302 loc) · 10 KB
/
multiple_lines_voronoi.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<!DOCTYPE html>
<!-- Modification of an example by Scott Murray from Knight D3 course -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Line Chart with Multiple Lines</title>
<style type="text/css">
body {
background-color: white;
font-family: Helvetica, Arial, sans-serif;
}
h1 {
font-size: 24px;
margin: 0;
}
p {
font-size: 14px;
margin: 10px 0 0 0;
width: 700px;
}
svg {
background-color: white;
}
path.line {
fill: none;
}
.unfocused {
stroke: gray;
stroke-width: 2px;
stroke-opacity: 0.8;
}
.focused {
stroke: orange;
stroke-opacity: 1;
stroke-width: 2px
}
.voronoi path {
stroke: none;
fill: none;
pointer-events: all;
}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 1px;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
text.linelabel {
font-size: 9pt;
color: gray;
}
circle {
fill: orange;
}
.tooltip {
position: absolute;
z-index: 10;
}
.tooltip p {
background-color: white;
border: gray 1px solid;
padding: 2px;
max-width: 180px;
}
</style>
</head>
<body>
<h1>CO2 Emissions by Country</h1>
<p>Carbon dioxide emissions, 1961-2010. Data not available for the entire period for all countries. Source: <a href="http://data.worldbank.org/indicator/EN.ATM.CO2E.KT?page=6">World Bank</a>, 2014. (Based on a modified example from Scott Murray.)</p>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script type="text/javascript">
//Dimensions and padding
var fullwidth = 700;
var fullheight = 600;
var margin = {top: 20, right: 120, bottom: 40, left:100};
var width = fullwidth - margin.left - margin.right;
var height = fullheight - margin.top - margin.bottom;
//Set up date formatting and years
var dateFormat = d3.time.format("%Y");
//Set up scales
var xScale = d3.time.scale()
.range([ 0, width ]);
var yScale = d3.scale.linear()
.range([0, height ]);
//Configure axis generators
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(15)
.tickFormat(function(d) {
return dateFormat(d);
})
.outerTickSize([0])
.innerTickSize([0]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.outerTickSize([0]);
//Configure line generator
// each line dataset must have a d.year and a d.amount for this to work.
var line = d3.svg.line()
.x(function(d) {
return xScale(dateFormat.parse(d.year));
})
.y(function(d) {
return yScale(+d.amount);
});
//Create the empty SVG image
var svg = d3.select("body")
.append("svg")
.attr("width", fullwidth)
.attr("height", fullheight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip");
//Load data
d3.csv("data/co2_emissions.csv", function(data) {
//New array with all the years, for referencing later
var years = ["1961", "1962", "1963", "1964", "1965", "1966", "1967", "1968", "1969", "1970", "1971", "1972", "1973", "1974", "1975", "1976", "1977", "1978", "1979", "1980", "1981", "1982", "1983", "1984", "1985", "1986", "1987", "1988", "1989", "1990", "1991", "1992", "1993", "1994", "1995", "1996", "1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007", "2008", "2009", "2010"];
// or you could get this by doing:
// var years = d3.keys(data[0]).slice(0, 54-4); //
//Create a new, empty array to hold our restructured dataset
var dataset = [];
//Loop once for each row in data
data.forEach(function (d, i) {
var myEmissions = [];
//Loop through all the years - and get the emissions for this data element
years.forEach(function (y) {
// If value is not empty
if (d[y]) {
//Add a new object to the new emissions data array - for year, amount
myEmissions.push({
country: d.countryName, // we can put the country in here too. It won't hurt.
year: y,
amount: d[y] // this is the value for, for example, d["2004"]
});
}
});
//Create new object with this country's name and empty array
// d is the current data row... from data.forEach above.
dataset.push( {
country: d.countryName,
emissions: myEmissions // we just built this!
} );
});
//Uncomment to log the original data to the console
// console.log(data);
//Uncomment to log the newly restructured dataset to the console
console.log(dataset);
//Set scale domains - max and mine of the years
xScale.domain(
d3.extent(years, function(d) {
return dateFormat.parse(d);
}));
// max of emissions to 0 (reversed, remember)
yScale.domain([
d3.max(dataset, function(d) {
return d3.max(d.emissions, function(d) {
return +d.amount;
});
}),
0
]);
//Make a group for each country
var groups = svg.append("g").attr("id", "lines")
.selectAll("g")
.data(dataset)
.enter()
.append("g")
.attr("class", "country")
.attr("id", function(d) {
if (d.country) {
return d.country.replace(/ |,|\./g, "_");
}
});
//Within each group, create a new line/path,
//binding just the emissions data to each one
groups
.append("path")
.classed("line", true)
.classed("unfocused", true)
.attr("d", function(d) {
d.line = this; // this isn't working for use below because it's the wrong dataset
return line(d.emissions);
})
.attr("id", function(d) {
if (d.country) {
return d.country.replace(/ |,|\./g, "_");
}
});
// Adding a subtle animation to increase the dot size when over it!
var voronoi = d3.geom.voronoi()
.x(function(d){
return xScale(dateFormat.parse(d.year));
})
.y(function(d) {
return yScale(+d.amount);
})
.clipExtent([[0, 0], [width, height]]);
var voronoiGroup = svg.append("g")
.attr("class", "voronoi");
// we have to do this nesting trick because a lot of dots are in the same place.
// the goal here is to map to single points -- no dupes at the same point -- and after
// the nesting, return just the actual values (not the keys).
// The values in a nest are the original items that went into each key.
var nested = d3.nest()
.key(function(d) { // this key is the pair of x/y coords - to keep them single
return xScale(dateFormat.parse(d.year)) + "," + yScale(+d.amount);
})
.rollup(function(v) {
return v[0]; // first of the objects, prevents use of 2 in same place
})
.entries(d3.merge(dataset.map(function(d) { return d.emissions; })))
.map(function (d) { return d.values;}); // the result is just a flat list of values
console.log(nested);
voronoiGroup.selectAll("path")
.data(voronoi(nested))
.enter()
.append("path")
.attr("d", function(d, i) {
return "M" + d.join("L") + "Z"; }) // this is just what you copy for a voronoi
.datum(function(d, i) { return d.point; }) // again, copy as is
.on("mouseover", mouseoverFunc) // mouseover goes on the voronoi cell!
.on("mousemove", mousemoveFunc)
.on("mouseout", mouseoutFunc);
// We're putting the text label at the group level, where the country name was originally.
groups.append("text")
.datum(function(d) {
return {name: d.country, value: d.emissions[d.emissions.length - 1]};
})
.attr("transform", function(d) {
// error on some with no d.value - American Samoa, for instance.
if (d.value) {
return "translate(" + xScale(dateFormat.parse(d.value.year)) + "," + yScale(+d.value.amount) + ")";
}
else {
return null;
}
})
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) {
if (d.value && +d.value.amount > 700000) {
return d.name;
}
})
.attr("class", "linelabel");
// the line's dot is the "focus" element
var focus = svg.append("g")
.attr("transform", "translate(-100,-100)") // it's off screen
.attr("class", "focus");
focus.append("circle")
.attr("r", 3.5);
focus.append("text")
.attr("y", -10);
//Axes
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function mouseoverFunc(d) {
// position the dot
focus.attr("transform", "translate(" + xScale(dateFormat.parse(d.year)) + "," + yScale(+d.amount) + ")");
// show the tooltip
tooltip
.style("display", null) // this removes the display none setting from it
.html("<p>Country: " + d.country +
"<br>Year: " + d.year +
"<br>Emissions: " + d.amount + " kt</p>");
var countryId = d.country.replace(/ |,|\./g, "_");
d3.select("path.line#" + countryId).classed("focused", true).classed("unfocused", false);
d3.select("g.country#" + countryId).moveToFront(); // the parent node is g#lines
}
function mousemoveFunc(d) {
tooltip
.style("top", (d3.event.pageY - 10) + "px" )
.style("left", (d3.event.pageX + 10) + "px");
}
function mouseoutFunc(d) {
// remove the dot offscreen and the tooltip
focus.attr("transform", "translate(-100,-100)");
d3.selectAll("path.line").classed("focused", false).classed("unfocused", true);
tooltip.style("display", "none"); // this sets it to invisible!
}
}); // end of data csv
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
}
</script>
</body>
</html>