-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
544 lines (450 loc) · 18.3 KB
/
Copy pathapp.js
File metadata and controls
544 lines (450 loc) · 18.3 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Load data
d3.csv("healthProcessedData.csv").then(data => {
console.log("Processed Data:", data); // Debug: Check processed data
// Parse year and search_count as numbers
data.forEach(d => {
d.year = +d.year; // Convert year to a number
d.search_count = +d.search_count; // Convert search_count to a number
});
// Group data by year and condition, summing search counts across cities
const groupedData = d3.rollup(
data,
v => d3.sum(v, d => d.search_count), // Sum search counts for each condition in each year
d => d.year, // Group by year
d => d.condition // Group by condition
);
// Convert grouped data to an array of objects
const raceData = Array.from(groupedData, ([year, conditions]) => ({
year,
conditions: Array.from(conditions, ([condition, search_count]) => ({
condition,
search_count
}))
}));
console.log("Race Data:", raceData); // Debug: Check race data
// ==================== Bar Chart Race ====================
createBarChartRace(raceData);
// ==================== Multi-Line Chart ====================
createMultiLineChart(raceData);
// ==================== Stacked Bar Chart ====================
createStackedBarChart(data);
// Add event listener for the year slider
const yearSlider = document.getElementById("year-slider");
const sliderValue = document.getElementById("slider-value");
yearSlider.addEventListener("input", () => {
const selectedYear = +yearSlider.value;
sliderValue.textContent = selectedYear;
createStackedBarChart(data, selectedYear);
});
}).catch(error => {
console.error("Error loading the data:", error);
});
// Function to create the bar chart race
function createBarChartRace(raceData) {
// Specify the chart’s dimensions.
const width = 800;
const height = 500;
const marginTop = 20;
const marginRight = 100; // Increased margin for year label
const marginBottom = 30;
const marginLeft = 100;
// Create the SVG container for the bar chart race.
const svg = d3.select("#bar-chart-race")
.append("svg")
.attr("width", width)
.attr("height", height);
// Create the horizontal scale (search counts).
const x = d3.scaleLinear()
.domain([0, d3.max(raceData, d => d3.max(d.conditions, c => c.search_count))])
.range([marginLeft, width - marginRight]);
// Create the vertical scale (conditions).
const y = d3.scaleBand()
.domain([]) // Will be updated dynamically
.range([marginTop, height - marginBottom])
.padding(0.1);
// Add x-axis.
const xAxis = svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`);
// Add y-axis.
const yAxis = svg.append("g")
.attr("transform", `translate(${marginLeft},0)`);
// Add a group for bars.
const bars = svg.append("g");
// Add a group for labels.
const labels = svg.append("g");
// Add a year label to the side.
const yearLabel = svg.append("text")
.attr("class", "year-label")
.attr("x", width - 80) // Adjusted position
.attr("y", height / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text("Year: 2004");
// Add a color scale.
const color = d3.scaleOrdinal(d3.schemeCategory10);
// Add a tooltip.
const tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
// Function to update the chart for a specific year.
function update(year) {
const yearData = raceData.find(d => d.year === year).conditions;
// Sort data by search count (descending).
yearData.sort((a, b) => b.search_count - a.search_count);
// Update the y-axis domain.
y.domain(yearData.map(d => d.condition));
// Update the x-axis.
xAxis.transition()
.duration(500)
.call(d3.axisBottom(x).ticks(width / 80, "s"));
// Update the y-axis.
yAxis.transition()
.duration(500)
.call(d3.axisLeft(y));
// Update bars.
const bar = bars.selectAll(".bar")
.data(yearData, d => d.condition);
bar.enter().append("rect")
.attr("class", "bar")
.attr("x", marginLeft)
.attr("y", d => y(d.condition))
.attr("width", d => x(d.search_count) - marginLeft)
.attr("height", y.bandwidth())
.attr("fill", d => color(d.condition))
.on("mouseover", function (event, d) {
// Highlight the bar.
d3.select(this)
.attr("fill-opacity", 1)
.attr("stroke", "#333")
.attr("stroke-width", 2);
// Show tooltip.
tooltip.transition()
.duration(200)
.style("opacity", 0.9);
tooltip.html(`Search Count: ${d.search_count}`)
.style("left", `${event.pageX + 5}px`)
.style("top", `${event.pageY - 28}px`);
})
.on("mouseout", function () {
// Restore the bar's appearance.
d3.select(this)
.attr("fill-opacity", 0.6)
.attr("stroke", null)
.attr("stroke-width", 0);
// Hide tooltip.
tooltip.transition()
.duration(200)
.style("opacity", 0);
})
.merge(bar)
.transition()
.duration(500)
.attr("y", d => y(d.condition))
.attr("width", d => x(d.search_count) - marginLeft);
bar.exit().remove();
// Update labels.
const label = labels.selectAll(".bar-label")
.data(yearData, d => d.condition);
label.enter().append("text")
.attr("class", "bar-label")
.attr("x", d => x(d.search_count) - 5)
.attr("y", d => y(d.condition) + y.bandwidth() / 2)
.attr("dy", "0.35em")
.text(d => d.condition)
.merge(label)
.transition()
.duration(500)
.attr("x", d => x(d.search_count) - 5)
.attr("y", d => y(d.condition) + y.bandwidth() / 2)
.text(d => d.condition);
label.exit().remove();
// Update the year label.
yearLabel.text(`Year: ${year}`);
}
// Get the list of years.
const years = raceData.map(d => d.year).sort((a, b) => a - b);
// Start the animation.
let currentYearIndex = 0;
let interval;
function animate() {
update(years[currentYearIndex]);
currentYearIndex = (currentYearIndex + 1) % years.length;
}
// Start the animation loop.
function startAnimation() {
interval = setInterval(animate, 1000);
}
// Stop the animation.
function stopAnimation() {
clearInterval(interval);
}
// Replay the animation.
d3.select("#replay").on("click", () => {
stopAnimation();
currentYearIndex = 0;
startAnimation();
});
// Pause/Continue the animation.
const pauseButton = d3.select("#pause");
pauseButton.on("click", () => {
if (pauseButton.text() === "Pause") {
stopAnimation();
pauseButton.text("Continue");
} else {
startAnimation();
pauseButton.text("Pause");
}
});
// Start the animation initially.
startAnimation();
}
// Function to create the multi-line chart
function createMultiLineChart(raceData) {
// Specify the chart’s dimensions.
const width = 800;
const height = 500;
const marginTop = 20;
const marginRight = 150; // Increased margin for the legend
const marginBottom = 50;
const marginLeft = 100;
// Create the SVG container for the multi-line chart.
const svg = d3.select("#multi-line-chart")
.append("svg")
.attr("width", width)
.attr("height", height);
// Create the horizontal scale (years).
const x = d3.scaleLinear()
.domain([d3.min(raceData, d => d.year), d3.max(raceData, d => d.year)]) // Domain: min to max year
.range([marginLeft, width - marginRight]); // Range: left to right margin
// Create the vertical scale (search counts).
const y = d3.scaleLinear()
.domain([0, d3.max(raceData, d => d3.max(d.conditions, c => c.search_count))]) // Domain: 0 to max search count
.range([height - marginBottom, marginTop]); // Range: bottom to top margin
// Add x-axis.
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).ticks(d3.max(raceData, d => d.year) - d3.min(raceData, d => d.year)));
// Add y-axis.
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y));
// Add a color scale using d3-scale-chromatic.
const color = d3.scaleOrdinal(d3.schemeCategory10);
// Create a line generator.
const line = d3.line()
.x(d => x(d.year)) // Map year to x-position
.y(d => y(d.search_count)); // Map search count to y-position
// Get unique conditions.
const conditions = [...new Set(raceData.map(d => d.conditions.map(c => c.condition)).flat())];
// Add lines for each condition.
const lines = svg.selectAll(".line")
.data(conditions)
.enter().append("path")
.attr("class", "line")
.attr("d", d => line(raceData.map(rd => ({
year: rd.year,
search_count: rd.conditions.find(c => c.condition === d)?.search_count || 0
}))))
.attr("stroke", d => color(d))
.attr("stroke-width", 2)
.attr("fill", "none");
// Add a group for hover effects.
const hoverGroup = svg.append("g")
.attr("display", "none");
// Add a circle to highlight the closest data point.
const hoverCircle = hoverGroup.append("circle")
.attr("r", 5)
.attr("fill", "steelblue")
.attr("stroke", "white")
.attr("stroke-width", 2);
// Add text to display the condition and search count.
const hoverText = hoverGroup.append("text")
.attr("font-size", 12)
.attr("font-family", "sans-serif")
.attr("text-anchor", "middle")
.attr("dy", "-0.5em");
// Add a vertical line to indicate the hovered year.
const hoverLine = hoverGroup.append("line")
.attr("stroke", "#000")
.attr("stroke-width", 1)
.attr("stroke-dasharray", "3,3");
// Add hover interaction.
svg.on("pointermove", function (event) {
const [xm, ym] = d3.pointer(event); // Get mouse position
const year = x.invert(xm); // Get the year corresponding to the mouse position
// Find the closest year in the data.
const closestYear = raceData.reduce((a, b) => Math.abs(a.year - year) < Math.abs(b.year - year) ? a : b);
// Find the closest condition and its search count.
let closestCondition = null;
let closestSearchCount = 0;
let minDistance = Infinity;
conditions.forEach(condition => {
const searchCount = closestYear.conditions.find(c => c.condition === condition)?.search_count || 0;
const distance = Math.abs(y(searchCount) - ym); // Distance between mouse and data point
if (distance < minDistance) {
minDistance = distance;
closestCondition = condition;
closestSearchCount = searchCount;
}
});
// Update the hover group.
if (closestCondition) {
hoverGroup.attr("display", null);
// Position the circle and text.
hoverCircle
.attr("cx", x(closestYear.year))
.attr("cy", y(closestSearchCount));
hoverText
.attr("x", x(closestYear.year))
.attr("y", y(closestSearchCount))
.text(`${closestCondition}: ${closestSearchCount}`);
// Position the vertical line.
hoverLine
.attr("x1", x(closestYear.year))
.attr("x2", x(closestYear.year))
.attr("y1", marginTop)
.attr("y2", height - marginBottom);
}
});
svg.on("pointerleave", () => {
hoverGroup.attr("display", "none"); // Hide hover effects when the mouse leaves the chart
});
// ==================== Add Legend ====================
const legend = svg.append("g")
.attr("transform", `translate(${width - marginRight + 20},${marginTop})`);
// Add one dot in the legend for each condition.
legend.selectAll("mydots")
.data(conditions)
.enter()
.append("circle")
.attr("cx", 0)
.attr("cy", (d, i) => i * 20) // 20 is the distance between dots
.attr("r", 5)
.style("fill", d => color(d));
// Add text in the legend for each condition.
legend.selectAll("mylabels")
.data(conditions)
.enter()
.append("text")
.attr("x", 10)
.attr("y", (d, i) => i * 20) // 20 is the distance between dots
.style("fill", d => color(d))
.text(d => d)
.attr("text-anchor", "left")
.style("alignment-baseline", "middle");
}
// Function to create the stacked bar chart
function createStackedBarChart(data, selectedYear = 2004) {
// Filter data for the selected year
const filteredData = data.filter(d => d.year === selectedYear);
// Group data by state_abb and condition
const groupedData = d3.rollup(
filteredData,
v => d3.sum(v, d => d.search_count), // Sum search counts for each condition in each state
d => d.state_abb, // Group by state
d => d.condition // Group by condition
);
// Convert grouped data to an array of objects
const chartData = Array.from(groupedData, ([state, conditions]) => {
const conditionData = Object.fromEntries(conditions);
return {
state,
...conditionData // Spread conditions into the object
};
});
console.log("Chart data:", chartData); // Debugging
// Clear the previous chart
d3.select("#stacked-bar-chart").html("");
// Set up dimensions
const margin = { top: 20, right: 30, bottom: 40, left: 40 };
const width = 800 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;
// Create SVG container
const svg = d3.select("#stacked-bar-chart")
.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})`);
// Hardcoded conditions and colors
const conditions = [
"cancer", "cardiovascular", "stroke", "depression",
"rehab", "vaccine", "diarrhea", "obesity", "diabetes"
];
const colors = [
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728",
"#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22"
];
// Create stacked data
const stack = d3.stack()
.keys(conditions)
.value((d, key) => d[key] || 0); // Use 0 if the condition doesn't exist for a state
const stackedData = stack(chartData);
console.log("Stacked data:", stackedData); // Debugging
// Create scales
const x = d3.scaleBand()
.domain(chartData.map(d => d.state))
.range([0, width])
.padding(0.1);
const y = d3.scaleLinear()
.domain([0, d3.max(stackedData, d => d3.max(d, d => d[1]))])
.nice()
.range([height, 0]);
// Add x-axis
const xAxis = svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x));
// Add y-axis
const yAxis = svg.append("g")
.call(d3.axisLeft(y));
// Add bars
const bars = svg.append("g")
.selectAll("g")
.data(stackedData)
.join("g")
.attr("fill", (d, i) => colors[i]); // Use hardcoded colors
bars.selectAll("rect")
.data(d => d)
.join("rect")
.attr("x", d => x(d.data.state))
.attr("y", d => y(d[1]))
.attr("height", d => y(d[0]) - y(d[1]))
.attr("width", x.bandwidth())
.append("title")
.text(d => `${d.data.state} - ${conditions[d.index]}: ${d[1] - d[0]}`); // Use hardcoded conditions
// Add legend
const legend = svg.append("g")
.attr("transform", `translate(${width + 20},0)`);
legend.selectAll("rect")
.data(conditions)
.join("rect")
.attr("x", 0)
.attr("y", (d, i) => i * 20)
.attr("width", 18)
.attr("height", 18)
.attr("fill", (d, i) => colors[i]); // Use hardcoded colors
legend.selectAll("text")
.data(conditions)
.join("text")
.attr("x", 24)
.attr("y", (d, i) => i * 20 + 9)
.attr("dy", "0.35em")
.text(d => d); // Use hardcoded conditions
// Add zoom functionality
const zoom = d3.zoom()
.scaleExtent([1, 10]) // Allow zooming between 1x and 10x
.on("zoom", (event) => {
const transform = event.transform;
// Update x-axis
xAxis.call(d3.axisBottom(x).scale(transform.rescaleX(x.copy().range([0, width]))));
// Update y-axis
yAxis.call(d3.axisLeft(y).scale(transform.rescaleY(y)));
// Update bars
bars.selectAll("rect")
.attr("x", d => transform.applyX(x(d.data.state)))
.attr("y", d => transform.applyY(y(d[1])))
.attr("height", d => transform.applyY(y(d[0])) - transform.applyY(y(d[1])))
.attr("width", x.bandwidth() / transform.k); // Adjust bar width based on zoom level
});
svg.call(zoom);
}