-
Notifications
You must be signed in to change notification settings - Fork 0
/
occupations.html
330 lines (282 loc) · 15 KB
/
occupations.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
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<title>Scene 2: Occupations and sleep</title>
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.min.js"></script>
<!-- Load d3-annotation -->
<script src="https://unpkg.com/d3-svg-annotation@2"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<p>Now we explores the relationship between occupations, sleep quality, and sleep duration. Engineers and lawyers have the best average sleep quality/duration out of all occupations, while scientists and sales representatives have the worst. However, most occupations have a wide variance in sleep quality/duration within. The highlighted area on the plot represents the highest variance observed for a single occupation (nurse, colored in purple). </p>
<p>Mouseover the dots for more details regarding a participant. Click on a bar to highlight all data for that occupation.</p>
</div>
<div id="scatterplot" class="chart-container"></div>
<div id="barchart" class="chart-container"></div>
<div class="button-container">
<button onclick="window.location.href='index.html'">Previous- gender and sleep</button>
<button onclick="window.location.href='age.html'">Next- age and sleep</button>
</div>
<script>
d3.csv("https://leemhmark.github.io/data/sleep_dataset.csv").then(function(data) {
// Parse data
const parsedData = data.map(d => ({
personId: +d["Person ID"],
gender: d["Gender"].toLowerCase(),
age: +d["Age"],
occupation: d["Occupation"],
sleepDuration: +d["Sleep Duration"],
sleepQuality: +d["Quality of Sleep"],
physicalActivityLevel: +d["Physical Activity Level"],
stressLevel: +d["Stress Level"],
bmiCategory: d["BMI Category"],
bloodPressure: d["Blood Pressure"],
heartRate: +d["Heart Rate"],
dailySteps: +d["Daily Steps"],
sleepDisorder: d["Sleep Disorder"]
}));
// Debugging: Log the parsed data to console
console.log(parsedData);
// Render Scatter Plot for Scene 1
const scatterPlotObj = scatterPlot(parsedData, 'sleepDuration', 'sleepQuality', 'occupation', '#scatterplot');
// Render Bar Chart for Scene 1
const barChartObj = barChart(parsedData, '#barchart', scatterPlotObj);
// Add event listener to reset points and bars when clicking outside bars
document.body.addEventListener('click', function() {
// Check if the click event is not on a bar or circle
if (!event.target.closest('.bar-quality') && !event.target.closest('.bar-duration') && !event.target.closest('.dot')) {
scatterPlotObj.resetPoints();
barChartObj.resetBars();
}
});
}).catch(function(error) {
// Debugging: Log the error if the CSV fails to load
console.error('Error loading or parsing the CSV file:', error);
});
const scatterPlot = (data, xField, yField, colorField, elementId) => {
const svg = d3.select(elementId).append("svg").attr("width", 1000).attr("height", 400);
const margin = { top: 20, right: 30, bottom: 60, left: 70 };
const width = svg.attr("width") - margin.left - margin.right;
const height = svg.attr("height") - margin.top - margin.bottom;
// Calculate the min and max values for the x and y fields
const xExtent = d3.extent(data, d => d[xField]);
const yExtent = d3.extent(data, d => d[yField]);
// Adjust the extents by 0.5
const extent_adjust = 1.0
xExtent[0] -= extent_adjust;
xExtent[1] += extent_adjust;
yExtent[0] -= extent_adjust;
yExtent[1] += extent_adjust;
const x = d3.scaleLinear().domain(xExtent).range([0, width]);
const y = d3.scaleLinear().domain(yExtent).range([height, 0]);
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
g.append("g").call(d3.axisLeft(y));
g.append("g").attr("transform", `translate(0,${height})`).call(d3.axisBottom(x));
// X Axis Label
svg.append("text")
.attr("transform", `translate(${margin.left + width / 2}, ${margin.top + height + 40})`)
.style("text-anchor", "middle")
.text("Sleep Duration (hours)");
// Y Axis Label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", margin.left - 50)
.attr("x", - (margin.top + height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Sleep Quality (scale 0-10)");
// Add annotation to the chart
const annotations = [
{
note: {
label: "Max range of sleep quality and durations for an occupation (nurse)",
},
type: d3.annotationCalloutRect,
subject: {
width: 455,
height: 210
},
x: x(6.2), // Use scale for positioning
y: y(8.85),
dy: -5,
dx: -5
}
];
const makeAnnotations = d3.annotation()
.accessors({
x: function(d){ return x(d.x) + margin.left; },
y: function(d){ return y(d.y) + margin.top; }
})
.annotations(annotations);
const annotationGroup = svg.append("g")
.attr("class", "annotation-group")
.call(makeAnnotations);
// Set pointer-events to none for the annotations
annotationGroup.selectAll(".annotation")
.style("pointer-events", "none");
// Define color scale for occupations
const colorScale = d3.scaleOrdinal(d3.schemeCategory10)
.domain([...new Set(data.map(d => d[colorField]))]);
const tooltip = d3.select("body").append("div").attr("class", "tooltip").style("opacity", 0);
const dots = g.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", d => x(d[xField]))
.attr("cy", d => y(d[yField]))
.attr("r", 5)
.style("fill", d => colorScale(d[colorField]))
.on("mouseover", function(event, d) {
tooltip.transition().duration(200).style("opacity", .9);
tooltip.html(`Person ID: ${d.personId}<br>Gender: ${d.gender}<br>Occupation: ${d.occupation}<br>Age: ${d.age}<br>Sleep Duration: ${d.sleepDuration}<br>Sleep Quality: ${d.sleepQuality}`)
.style("left", (event.pageX + 5) + "px").style("top", (event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
tooltip.transition().duration(500).style("opacity", 0);
});
// Raise circles to the front
dots.raise();
// Function to highlight points based on occupation
function highlightPoints(occupation) {
dots.transition().duration(200)
.style("opacity", d => d.occupation === occupation ? 1 : 0);
}
// Function to reset points opacity
function resetPoints() {
dots.transition().duration(200)
.style("opacity", 1);
d3.select("#annotation-occupation-scatter").style("display", "none");
d3.select("#annotation-sleep-duration").style("display", null);
}
// Add legend
const legend = svg.append("g")
.attr("transform", `translate(${width + margin.left -90}, ${margin.top})`);
const occupations = [...new Set(data.map(d => d[colorField]))];
occupations.forEach((occupation, i) => {
legend.append("circle")
.attr("cx", 0)
.attr("cy", i * 20)
.attr("r", 5)
.style("fill", colorScale(occupation));
legend.append("text")
.attr("x", 10)
.attr("y", i * 20 + 5)
.text(occupation)
.style("font-size", "12px")
.attr("alignment-baseline","middle");
});
return { highlightPoints, resetPoints };
};
const barChart = (data, elementId, scatterPlotObj) => {
const svg = d3.select(elementId).append("svg").attr("width", 1000).attr("height", 300);
const margin = { top: 20, right: 30, bottom: 80, left: 70 };
const width = svg.attr("width") - margin.left - margin.right;
const height = svg.attr("height") - margin.top - margin.bottom;
// Calculate average sleep quality and duration by occupation
const avgData = d3.rollup(data, v => ({
avgSleepQuality: d3.mean(v, d => d.sleepQuality),
avgSleepDuration: d3.mean(v, d => d.sleepDuration)
}), d => d.occupation);
const avgDataArray = Array.from(avgData, ([key, value]) => ({ key, ...value }));
// Sort the data by decreasing sleep quality
avgDataArray.sort((a, b) => b.avgSleepQuality - a.avgSleepQuality);
const x = d3.scaleBand().domain(avgDataArray.map(d => d.key)).range([0, width]).padding(0.3); // Increase padding for narrower bars
const y0 = d3.scaleLinear().domain([0, 10]).range([height, 0]); // Sleep quality scale
const y1 = d3.scaleLinear().domain([0, 10]).range([height, 0]); // Sleep duration scale
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
g.append("g").call(d3.axisLeft(y0));
g.append("g").attr("transform", `translate(0,${height})`).call(d3.axisBottom(x)).selectAll("text").attr("transform", "rotate(-30)").style("text-anchor", "end");
const barWidth = x.bandwidth() / 3; // Adjust bar width for narrower bars
// Function to highlight bars based on occupation
function highlightBars(occupation) {
g.selectAll(".bar-quality")
.transition().duration(200)
.style("opacity", d => d.key === occupation ? 1 : 0.2);
g.selectAll(".bar-duration")
.transition().duration(200)
.style("opacity", d => d.key === occupation ? 1 : 0.2);
}
// Function to reset bars opacity
function resetBars() {
g.selectAll(".bar-quality")
.transition().duration(200)
.style("opacity", 1);
g.selectAll(".bar-duration")
.transition().duration(200)
.style("opacity", 1);
}
// Bar for average sleep quality
g.selectAll(".bar-quality")
.data(avgDataArray)
.enter().append("rect")
.attr("class", "bar-quality")
.attr("x", d => x(d.key))
.attr("y", d => y0(d.avgSleepQuality))
.attr("width", barWidth)
.attr("height", d => height - y0(d.avgSleepQuality))
.attr("fill", "#1f77b4")
.on("click", function(event, d) {
event.stopPropagation(); // Prevent this event from bubbling up to the body
scatterPlotObj.highlightPoints(d.key);
highlightBars(d.key);
})
.on("mouseover", function(event, d) {
d3.select(this)
.attr("fill", "#3498db") // Change color on hover
.attr("transform", `translate(0, -10)`); // Make the bars pop out
})
.on("mouseout", function(event, d) {
d3.select(this)
.attr("fill", "#1f77b4") // Revert color
.attr("transform", `translate(0, 0)`);
});
// Bar for average sleep duration
g.selectAll(".bar-duration")
.data(avgDataArray)
.enter().append("rect")
.attr("class", "bar-duration")
.attr("x", d => x(d.key) + barWidth + 5) // Add space between the bars
.attr("y", d => y1(d.avgSleepDuration))
.attr("width", barWidth)
.attr("height", d => height - y1(d.avgSleepDuration))
.attr("fill", "#ff7f0e")
.on("click", function(event, d) {
event.stopPropagation(); // Prevent this event from bubbling up to the body
scatterPlotObj.highlightPoints(d.key);
highlightBars(d.key);
})
.on("mouseover", function(event, d) {
d3.select(this)
.attr("fill", "#ffbb78") // Change color on hover
.attr("transform", `translate(0, -10)`);
})
.on("mouseout", function(event, d) {
d3.select(this)
.attr("fill", "#ff7f0e") // Revert color
.attr("transform", `translate(0, 0)`);
});
// X Axis Label
svg.append("text")
.attr("transform", `translate(${margin.left + width / 2}, ${margin.top + height + 60})`)
.style("text-anchor", "middle")
.text("Gender");
// Y Axis Label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", margin.left - 50)
.attr("x", - (margin.top + height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Average Sleep Duration and Quality");
// Legend
g.append("rect").attr("x", width - 180).attr("y", -20).attr("width", 10).attr("height", 10).style("fill", "#1f77b4");
g.append("text").attr("x", width - 165).attr("y", -10).text("Sleep Quality (0-10 scale)").style("font-size", "12px").attr("alignment-baseline","middle");
g.append("rect").attr("x", width - 180).attr("y", 0).attr("width", 10).attr("height", 10).style("fill", "#ff7f0e");
g.append("text").attr("x", width - 165).attr("y", 10).text("Sleep Duration (hours)").style("font-size", "12px").attr("alignment-baseline","middle");
return { highlightBars, resetBars };
};
</script>
</body>
</html>