-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvis.js
More file actions
407 lines (371 loc) · 12.8 KB
/
Copy pathvis.js
File metadata and controls
407 lines (371 loc) · 12.8 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
import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/+esm";
// Declare the chart dimensions and margins.
const margin = {
left: 80,
bottom: 50,
right: 100,
top: 70
}
const width = 980 - margin.left - margin.right
const height = 600 - margin.top - margin.bottom
// Declare x scale
const x = d3.scaleLinear()
.domain([-0.05, 0.06])
.range([0, width]);
// Declare y scale
const y = d3.scaleLinear()
.domain([-0.04, 0.05])
.range([height, 0]);
// Create SVG container
const svg = d3.select("#container")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("role", "img")
.attr("aria-labelledby", "wwp-title")
.attr("aria-describedby", "wwp-desc")
// Create svg title for aria attributes
svg
.attr("role", "img")
.attr("aria-label", "PCA scatter plot for the Women Writers Project");
// Create svg desc for aria attributes
svg
.append("desc")
.attr("id", "wwp-desc")
.text(`This is a scatter plot plotting the Principal Component Analysis (PCA) outputs of writers from Northeastern University's
Women Writers Project. Points are plotted by PCA values, colored by author, and shaped by their genre.`)
// move to-be graphic within the margin
const dataRegion = svg
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
// Add the Title
// I'm using this separately than the accessible <title>, I think this should be still good practice from what I've read.
svg.append("text")
.attr("id", "graph-title")
.attr("x", width / 2 + margin.left) //positions it at the middle of the width
.attr("y", margin.top / 2) //positions it from the top by the margin top
.text("Principal Component Analysis Scatterplot");
// Add x-axis
dataRegion.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(x))
// Add x-axis label
svg.append("text")
.attr("id", "x-axis")
.attr("x", width / 2 + margin.left)
.attr("y", height + margin.top + 40)
.text("PC1");
// Add the y-axis.
dataRegion.append("g")
.attr("transform", `translate(0,0)`)
.call(d3.axisLeft(y))
// Add y-axis label
svg.append("text")
.attr("id", "y-axis")
.attr("x", margin.left - 40)
.attr("y", height / 2 + margin.top)
.attr("fill", "currentColor")
.text("PC2");
// Create the tooltip box
const tooltip = d3.select("#container")
.append("div")
.attr("class", "tooltip")
const FEATURED_AUTHORS = [
"Behn, Aphra",
"Cavendish, Margaret (Lucas), Duchess of Newcastle",
"Davies, Lady Eleanor",
"Elizabeth I",
"Haywood, Eliza (Fowler)",
"Philips, Katherine (Fowler)"
]
// Creates a global state where all data on genres/centuries, authors, colors, shapes can be kept
const state = {
authors: new Set(),
genres: new Set(),
color: null,
shape: null,
activeAuthors: new Set(),
activeGenres: new Set(),
allAuthors: new Set(),
featuredAuthors: FEATURED_AUTHORS,
shapeField: "Genre"
};
/**
* This function creates the author selector list. This is the multiselect box of checkboxes
* that allows users to select which authors they want to be colored for filtering.
*/
function createAuthorSelector(data) {
// edit state to a list of all authors
state.allAuthors = [...new Set(data.map(d => d['Author']))].sort();
// select the author-checkboxes div and assign to container
const container = d3.select("#author-checkboxes");
// Select all divs inside the container, and create a div for each author
const items = container.selectAll("div")
.data(state.allAuthors)
.join("div")
.attr("class", "author-select")
// append an input checkbox to each div
items.append("input")
.attr("type", "checkbox")
.attr("value", d => d)
.attr("id", d => `select-${d}`)
.property("checked", d => state.featuredAuthors.includes(d));
// append a label for the checkbox in each div
items.append("label")
.attr("for", d => `select-${d}`)
.text(d => d);
// Handle checkbox changes: this first checks to make sure there are at most 6 authors selected
// and then assigns the featured authors to the selected checkbox nodes and redraws the plot
d3.select("#author-change-button")
.on("click", function () {
const checked = container.selectAll("input:checked").nodes();
if (checked.length > 6) {
this.checked = false;
alert("Maximum 6 authors allowed");
return;
}
state.featuredAuthors = checked.map(el => el.value);
reset();
draw(globalData);
})
// This button clears all of the selected checkboxes
d3.select('#clear-selection-button')
.on("click", function () {
container.selectAll("input:checked")
.property("checked", false)
})
// This button restores the selection to the top six authors based on text count
d3.select('#restore-button')
.on("click", function () {
state.featuredAuthors = FEATURED_AUTHORS
reset();
draw(globalData);
})
}
/**
* Create the legend for the author fields
*/
function authorLegendCreate(){
// d3 data join
const authorLegend = d3.select("#author-legend")
.selectAll("span")
.data(state.authors)
.join("span");
// creating the checkbox with functionality
authorLegend.append("input")
.attr("type", "checkbox")
.attr("id", d => `${d}-control`)
.attr("name", "author-method")
.attr("value", d => d)
.attr("checked", true)
.on("change", function(event, d) {
if (state.activeAuthors.has(d)) {
state.activeAuthors.delete(d);
} else {
state.activeAuthors.add(d)
}
updatePointVisibility()});
// create the circle symbol for each author
authorLegend.append("svg")
.attr("width", 15)
.attr("height", 15)
.append("path")
.attr("transform", "translate(9,9)")
.attr("d", d3.symbol())
.style("fill", d => state.color(d))
// Name
authorLegend.append("label")
.attr("for", d => `${d}-control`)
.text(d => d)
}
/**
* Create the genre/century legend and shapes
*/
function genreLegendCreate(){
// rename the legend name
d3.select("#genre-legend legend")
.text(state.shapeField === "Genre" ? "Genre" : "Time Period");
// d3 data join
const genreLegend = d3.select("#genre-legend")
.selectAll("span")
.data(state.genres)
.join("span");
// checkbox and interactivity
genreLegend.append("input")
.attr("type", "checkbox")
.attr("id", d => `${d}-control`)
.attr("name", "genre-method")
.attr("value", d => d)
.attr("checked", true)
.on("change", function(event, d) {
if (state.activeGenres.has(d)) {
state.activeGenres.delete(d);
} else {
state.activeGenres.add(d)
}
updatePointVisibility()});
// appending the shape
genreLegend.append("svg")
.attr("width", 15)
.attr("height", 15)
.append("path")
.attr("transform", "translate(9, 9)")
.attr("d", d => d3.symbol().type(state.shape(d)).size(50)())
.attr("fill", "black")
// name
genreLegend.append("label")
.attr("for", d => `${d}-control`)
.text(d => d)
}
/**
* This function returns the shape scale based on whether it will be the century or the genre
*
* @param {*} shapeField: the column name for the shapefield, either Simple Genre or Simple Date
* @param {*} data: the CSV data
* @returns
*/
function createShapeScale(shapeField, data) {
const domain = shapeField === "Genre"
? ["drama", "non-fiction", "verse", "fiction"]
: [...new Set(data.map(d => d[shapeField]))];
const shape = d3.scaleOrdinal()
.domain(domain)
.range(d3.symbols);
return shape;
}
/**
* This function creates the author scale based on color
*
* @param {*} data: the CSV data
* @returns
*/
function createAuthorScale(data) {
// Add a column to the dataset of either the author name or Other if they
// have are not in the FEATURED_AUTHORS list
data.forEach(d => {
d.AuthorGrouped = state.featuredAuthors.includes(d['Author']) ? d['Author'] : "Other"
})
const color = d3.scaleOrdinal()
.domain(data.map(d => d.AuthorGrouped))
.range(['#325981', '#EE6677', '#228833', '#a19436', '#43a1b1', '#AA3377', '#888888'])
return color
}
/**
* Updates the point visibilities based on genre/century and author
*/
function updatePointVisibility() {
dataRegion.selectAll("path.data-point").each(function (d) {
// Get the author and genre from the point's classes or data
const point = d3.select(this);
// Point is visible only if BOTH its author and genre are active
const isVisible = state.activeAuthors.has(d.AuthorGrouped) &&
state.activeGenres.has(d[state.shapeField]);
// transition
point.interrupt()
.transition()
.style("opacity", isVisible ? 1 : 0.1)
.style("pointer-events", isVisible ? "all" : "none");
});
}
/**
* Creates the reset button
*/
function resetButton(){
d3.select("#reset-button")
.on("click", function () {
// clear the state and repopulate it with all authors/genres
state.activeAuthors.clear();
state.authors.forEach(a => state.activeAuthors.add(a));
state.activeGenres.clear();
state.genres.forEach(g => state.activeGenres.add(g));
// Update the point visibility
updatePointVisibility();
// Reset all button filters
d3.selectAll(".legends #genre-legend input").property("checked", true)
d3.selectAll(".legends #author-legend input").property("checked", true)
});
}
/**
*
* This function plots all of the points on the graph
*
* @param {*} data: The csv data
*/
function plotPoints(data){
// add data
dataRegion.append('g')
.selectAll("path")
.data(data)
.join("path")
// symbol
.attr("d", d3.symbol()
.type(function (d) { return state.shape(d[state.shapeField]); })
.size(40))
// position
.attr("transform", function (d) {
return `translate(${x(d.PC1)}, ${y(d.PC2)})`;
})
// setting class - this is mainly for activating and muting
.attr("class", function (d) { return `data-point ${d[state.shapeField]} ${d['AuthorGrouped']}` })
// color
.style("fill", d => state.color(d.AuthorGrouped))
// mouseover tooltip function
.on("mouseover", function (event, d) {
tooltip.transition().duration(200).style("opacity", .9);
tooltip.html(`Title: ${d['Display title']}<br>Author: ${d['Author']}<br>PC1: ${d.PC1}<br>PC2: ${d.PC2}<br>Genre: ${d['Genre']}<br>Period: ${d['Period']}`)
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px");
})
.on("mouseout", function (event, d) {
tooltip.transition().duration(200).style("opacity", 0);
});
}
/**
* This function runs all of the code to draw all parts of the visualization
*
* @param {*} data: The CSV data
*/
function draw(data) {
state.shape = createShapeScale(state.shapeField, data)
state.color = createAuthorScale(data)
state.authors = new Set(state.color.domain());
state.genres = new Set(state.shape.domain());
state.activeAuthors = new Set(state.color.domain());
state.activeGenres = new Set(state.shape.domain());
plotPoints(data)
genreLegendCreate()
authorLegendCreate()
createAuthorSelector(data)
resetButton();
}
// attaching the functionality for the genre/century switcher radio button
d3.selectAll("#shape-field-selector input")
.on("change", function(event, d) {
const selectedValue = event.target.value;
reset();
state.shapeField = selectedValue
draw(globalData);
});
/**
* This function resets and removes the relevant parts of the graph to be redrawn
*/
function reset() {
d3.selectAll("path.data-point")
.remove();
d3.select("#genre-legend")
.selectAll("span")
.remove()
d3.select("#author-legend")
.selectAll("span")
.remove()
d3.select("#author-checkboxes")
.selectAll("div")
.remove()
d3.select("#reset-button").on("click", null);
}
// specifying the global data and drawing the graph.
let globalData;
d3.csv("1600-1720-wwo_pca.csv").then(function(data) {
globalData = data;
draw(globalData);
});