-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1020 lines (858 loc) · 32.2 KB
/
index.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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>What factors impact the rating of a book?</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.gridlines line {
stroke: #d9bca3;
}
.gridlines .domain {
stroke: #d9bca3;
}
body,
html {
padding: 0;
margin: 0;
background-color: #362118;
font-family: 'Optima', sans-serif;
}
button {
padding: 10px;
margin: 15px 2px 15px 2px;
border: 1px solid #9d795e;
transition: background-color 0.2s ease, transform 0.1s ease;
font-family: 'Optima', sans-serif;
font-size: 14px;
}
button:hover {
border: 1px solid #362118;
/* Darker blue when clicked */
transform: scale(0.95);
/* Thicker border on hover */
}
h2 {
color: #fdb872;
font-size: 1.5rem;
}
p {
color: #f5d9be;
font-size: 18px;
line-height: 1.5;
}
.page-title {
font-size: 2.5rem;
font-weight: bold;
text-align: center;
margin: auto;
padding: 30px;
background-color: #f5d9be;
color: #362118;
width: 80vw;
}
.main {
background-color: #5e4336;
width: 80vw;
padding: 30px;
margin: auto;
}
.scatterplot {
display: flex;
margin: 10px 50px 10px 50px;
}
#dropdown {
background-color: #f5d9be;
font-family: 'Optima', sans-serif;
font-size: 20px;
padding: 10px;
margin: 10px 20px 10px 20px;
}
</style>
</head>
<body>
<h1 class="page-title">Key Factors That Influence Book Ratings</h1>
<div class="main">
<h2 style="margin-left: 50px">Top Rated Books by Genre</h2>
<p style="margin: 20px 50px 20px 50px">Our bookshelf visualization shows how the ratings of books compare between
genres. The average rating of our
dataset was calculated for each genre and sorted so that the top shelf has the highest-rated genre and the bottom
shelf has the lowest-rated genre. The higher-rated books are taller and have a darker hue, while the lower-rated
books are shorter and have a lighter hue, as shown in the legend above. However, it's important
to note that this correlation does not imply causation, which means the genre doesn't necessarily positively or
negatively impact the rating of a book. It appears
that historical fiction has the highest-rated books on average, and mystery has the lowest. </p>
<svg id="shelf" height="650" width="900" style="display: block; margin: auto">
<image x="-45" y="-25" height="710" width="950" href="shelf_bg.jpg" />
<g fill="#5e4336">
<!-- Shelf backs -->
<rect x="180" y="90" width="550" height="100" fill="#9d795e" />
<rect x="180" y="190" width="550" height="100" fill="#9d795e" />
<rect x="180" y="290" width="550" height="100" fill="#9d795e" />
<rect x="180" y="390" width="550" height="100" fill="#9d795e" />
<rect x="180" y="490" width="550" height="100" fill="#9d795e" />
<!-- Shelf pillars -->
<rect x="180" y="90" width="25" height="500" />
<rect x="705" y="90" width="25" height="500" />
<!-- Horizontal shelves -->
<rect x="180" y="90" width="550" height="25" />
<rect x="180" y="190" width="550" height="25" />
<rect x="180" y="290" width="550" height="25" />
<rect x="180" y="390" width="550" height="25" />
<rect x="180" y="490" width="550" height="25" />
<rect x="180" y="590" width="550" height="25" />
</g>
</svg>
<br>
<script>
const legendSvg = d3.select("#shelf");
const legendWidth = +legendSvg.attr("width");
const legendHeight = +legendSvg.attr("height");
const lowRatedColor = "white";
const highRatedColor = "#3b3b3b";
const bookWidthLegend = 10;
const bookHeightLegendMin = 20;
const bookHeightLegendMax = 50;
const padding = 20;
const legendXStart = legendWidth - 150;
const legendYStart = padding;
// Low-rated book label
legendSvg.append("text")
.attr("x", 225)
.attr("y", 55)
.style("text-anchor", "middle")
.style("font-size", "12px")
.text("Low-rated book:");
// Low-rated book rectangle
legendSvg.append("rect")
.attr("x", 225)
.attr("y", 65)
.attr("width", bookWidthLegend)
.attr("height", bookHeightLegendMin)
.style("fill", lowRatedColor)
.style("stroke", "black");
// High-rated book label
legendSvg.append("text")
.attr("x", 325)
.attr("y", 25)
.style("text-anchor", "middle")
.style("font-size", "12px")
.text("High-rated book:");
// High-rated book rectangle
legendSvg.append("rect")
.attr("x", 325)
.attr("y", 35)
.attr("width", bookWidthLegend)
.attr("height", bookHeightLegendMax)
.style("fill", highRatedColor)
.style("stroke", "black");
legendSvg.append("circle")
.attr("cx", 590)
.attr("cy", 75)
.attr("r", 3)
.style("fill", "gold")
.style("stroke", "black");
legendSvg.append("text")
.attr("x", 600)
.attr("y", 76)
.style("dominant-baseline", "middle")
.text("Award-winning book")
.style("font-size", "12px")
</script>
<div class="scatterplot">
<div>
<div style="display:flex">
<h2>Select a Factor</h2>
<select id="dropdown"></select>
</div>
<p style="margin-right: 30px" id="observations"></p>
</div>
<div>
<button id="Historical_Fiction">Historical Fiction</button>
<button id="Romance">Romance</button>
<button id="Nonfiction">Nonfiction</button>
<button id="Science_Fiction">Science Fiction</button>
<button id="Mystery">Mystery</button>
<button id="All_Genres">All Genres</button>
<svg id="scatterplot" width="606" height="500"></svg>
</div>
</div>
</div>
<script>
const svg = d3.select("svg");
const width = svg.attr("width");
const height = svg.attr("height");
const spaceBetweenBooks = 1;
const booksPerShelf = 50;
const bookWidth = (width - 4 * 102) / booksPerShelf - 1;
const shelfHeight = 100;
const minHeight = bookWidth * 2;
const maxHeight = shelfHeight - 27;
let defs = svg.append("defs");
// helper function: interactivity for books
function textCutoff(text, maxLength) {
if (text.length > maxLength) {
return text.substring(0, maxLength - 2).concat("...")
} else {
return text
}
}
// helper function: adds labels for each shelf which genre the books are
function addText(genre, shelfposition) {
let lengths = new Map([["Historical Fiction", 100],
["Romance", 60],
["Nonfiction", 70],
["Science Fiction", 90],
["Mystery", 60]])
svg.append("rect")
.attr("width", lengths.get(genre))
.attr("height", 15)
.attr("x", 207)
.attr("y", shelfposition - 11)
.style("fill", "#f0f0f0")
.style("stroke", "#222222")
.style("stroke-width", 1.5)
svg.append("text")
.attr("x", 211)
.attr("y", shelfposition)
.text(genre)
.style("font-size", "12px")
.style("font-weight", "bold")
.style("fill", "black");
}
function addYear(firstYear, lastYear, yearposition) {
svg.append("rect")
.attr("x", 186)
.attr("y", yearposition)
.attr("width", 13)
.attr("height", 50)
.style("fill", "#e4d5b7")
.style("stroke", "black");
svg.append("rect")
.attr("x", 710)
.attr("y", yearposition)
.attr("width", 13)
.attr("height", 50)
.style("fill", "#e4d5b7")
.style("stroke", "black");
for (let i = 0; i < 4; i++) {
svg.append("text")
.attr("x", 190)
.attr("y", yearposition + 13 + 10 * i)
.text(firstYear[i])
.style("font-size", "10px")
.style("font-weight", "bold")
.style("fill", "black");
svg.append("text")
.attr("x", 714)
.attr("y", yearposition + 13 + 10 * i)
.text(lastYear[i])
.style("font-size", "10px")
.style("font-weight", "bold")
.style("fill", "black");
}
}
// helper function: one compact function that parses all dates/times/years
// possible toFormats: 'year' i.e. 2024, 'date' i.e. Tue Jun 13 2017 00:00:00 GMT-0400 (Eastern Daylight Time)
function parseTime(date, toFormat) {
let parser = d3.timeFormat();
if (toFormat == 'year') {
parser = d3.timeFormat("%Y");
}
else if (toFormat == 'date') {
parser = d3.timeParse("%d-%b-%y");
}
else if (toFormat == 'str') {
parser = d3.utcFormat("%B %d, %Y");
}
return parser(date);
}
// helper function: darken a color
// inspired by lighten(color) from Prof. Rzeszotarski
function darken(color, amount) {
let hclColor = d3.hcl(color);
let luma = Math.min(130, hclColor.l - amount);
return d3.rgb(d3.hcl(hclColor.h, hclColor.c, luma));
}
// helper function: returns label without _ and capitalized
function formatLabel(text, type) {
if (text == "num_pages") {
text = "number_of_pages"
}
formatted = text.toLowerCase()
.split('_')
.map(s => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
return formatted
}
// helper function: creates rect/text for the hover label over books/circles
function createHoverLabel(label, uniqueBooks, awards_books) {
const labelWidth = 250;
const labelHeight = 110;
const r = 20;
label.append("rect")
.attr("width", labelWidth)
.attr("height", labelHeight)
.attr("rx", 10)
.attr("ry", 10)
.attr("fill", "#f5d9be")
.attr("stroke", "#362119");
label.append("text")
.attr("id", "labelTitle")
.attr("x", 10)
.attr("y", 20)
.style("font-size", "14px")
.style("font-weight", "bold");
label.append("text")
.attr("id", "labelAuthors")
.attr("x", 10)
.attr("y", 40)
.style("font-size", "12px");
label.append("text")
.attr("id", "labelGenre")
.attr("x", 10)
.attr("y", 60)
.style("font-size", "12px");
label.append("text")
.attr("id", "labelRating")
.attr("x", 10)
.attr("y", 80)
.style("font-size", "12px");
label.append("text")
.attr("id", "labelXVar")
.attr("x", 10)
.attr("y", 100)
.style("font-size", "12px");
label.append("circle")
.attr("id", "labelAward")
.attr("cx", labelWidth - r - 15) // Position near bottom-right corner
.attr("cy", labelHeight - r - 15)
.attr("r", r)
.style('fill', makeAwardSticker(r, labelWidth - r - 15, labelHeight - r - 15))
return label;
}
// Clips a star sticker onto the current circle
function makeAwardSticker(r, x, y) {
pattern = defs.append("pattern")
.attr("id", "star")
.attr("width", r * 2)
.attr("height", r * 2)
.attr("x", x + r)
.attr("y", y + r)
.attr("patternUnits", "userSpaceOnUse");
pattern.append("svg:image")
.attr("xlink:href", 'star.png')
.attr("width", r * 2)
.attr("height", r * 2)
.attr("x", 0)
.attr("y", 0);
return "url(#star)"
}
const requestData = async function () {
let data = await d3.csv('data/goodreads_top100_from1980to2023_final.csv');
let data_awards = await d3.csv('data/books_awards_chars.csv');
let plot_observations = await d3.json('data/plot_observations.json');
console.log("data", data);
console.log("data_awards", data_awards);
console.log("plot observations", plot_observations);
let num_genres = new Map() // map of genres to # of books
let genres_books = new Map()
let genres = ['Historical Fiction', 'Romance', 'Nonfiction', 'Science Fiction', 'Mystery']
// The books where one of the genres is among the top 5 genres
let top_genre_books = []
let awards_books = []
genres.forEach((g) => {
num_genres.set(g, 0);
})
data.forEach((d, i) => {
let genres_list = d['genres'].slice(2, -2).split("', '") // get list of genres for book
let len = genres_list.length;
// find first genre that's in top 5 genres
var i = 0;
let genre = genres_list[i];
while (!num_genres.has(genre)) {
i += 1;
if (i == len) {
genre = "";
break;
} else {
genre = genres_list[i];
}
}
// at this point, 'genre' is the genre (within top 5) of the book
d['top_genre'] = genre; // adding the top genre as a new field
// Reformatting some data
convert_to_num = ['current_readers', 'num_pages', 'num_ratings', 'num_reviews',
'price', 'rating_score', 'want_to_read'];
convert_to_num.forEach((category, i) => {
d[category] = Number(d[category]);
});
// date format from excel: e.g. "13-Jun-17"
d['publication_date'] = parseTime(d['publication_date'], 'date');
// fill map with counts of books
if (genre != "") {
num_genres.set(genre, num_genres.get(genre) + 1)
}
// add valid points to the dataset for scatterplots
if (genre != "" && d['num_pages'] > 0 && d['num_pages'] < 1800
&& parseTime(d['publication_date'], 'year') <= 2024 && d['price'] > 0) {
top_genre_books.push(d);
}
});
data_awards.forEach((d, i) => {
let genres_list = d['genres'].slice(2, -2).split("', '") // get list of genres for book
let len = genres_list.length;
// find first genre that's in top 5 genres
var i = 0;
let genre = genres_list[i];
while (!num_genres.has(genre)) {
i += 1;
if (i == len) {
genre = "";
break;
} else {
genre = genres_list[i];
}
}
// at this point, 'genre' is the genre (within top 5) of the book
d['top_genre'] = genre; // adding the top genre as a new field
// Reformatting some data
convert_to_num = ['rating'];
convert_to_num.forEach((category, i) => {
d[category] = Number(d[category]);
});
d['authors'] = d['author'];
d['rating_score'] = d['rating'];
// collect # of awards per book
let awards_split = d['awards'].slice(2, -2).split("', '");
d['number_of_awards'] = awards_split[0] == "" ? 0 : awards_split.length;
// add valid points to the dataset for scatterplots
if (genre != "" && d['pages'] > 0 && d['price'] > 0 && d['number_of_awards'] > 0) {
awards_books.push(d);
}
});
console.log("top_genre_books", top_genre_books);
console.log("awards_books", awards_books);
const uniqueBooks = [];
const seenBooks = new Set();
top_genre_books.forEach(book => {
if (!seenBooks.has(book.title)) {
uniqueBooks.push(book);
seenBooks.add(book.title);
}
})
// Add awarded column
data.forEach(d => {
if (awards_books.some(book2 => book2.title === d.title && book2.number_of_awards > 0)) {
d['awarded'] = true
} else {
d['awarded'] = false
}
})
// ----- Books on Shelf -----
// Genre color scale
// colors based on d3.schemeTableau10, but ordered differently
// pink, blue, purple, green, orange
const genreColors = ['#4F79A7', '#E1575A', '#AF7AA1', '#58A14E', '#F28E2C'];
const genreScale = d3.scaleOrdinal(genres, genreColors);
// subset of books to be added to the bookshelf
const booksForShelf = []
/*
for each genre, take the first 15 books that have this genre as its top genre
Note: dataset is sorted by highest number of reviews first
*/
genres.forEach(genre => {
let booksInGenre = uniqueBooks.filter(d => (d.top_genre === genre))
.slice(0, booksPerShelf)
booksInGenre.sort(function (a, b) {
return a["publication_date"] - b["publication_date"]
});
booksForShelf.push(booksInGenre);
})
console.log("booksForShelf", booksForShelf);
// get average rating per shelf
const genreRatingsMap = new Map();
booksForShelf.forEach(genre => {
let totalRating = 0
for (let i = 0; i < genre.length; i++) {
totalRating += genre[i].rating_score
}
genreRatingsMap.set(genre[0].top_genre, totalRating / genre.length)
})
// turn booksForShelf into a map of genres to the books in the genre
const shelfMap = new Map()
booksForShelf.forEach(array => {
shelfMap.set(array[0].top_genre, array)
})
console.log("shelfMap", shelfMap)
// sort genre list with ratings by highest ratings
const genreRatingsArr = [...genreRatingsMap.entries()].sort((a, b) => b[1] - a[1])
console.log("genreRatingsArr", genreRatingsArr)
const minRating = d3.min(booksForShelf.flat(), d => d.rating_score);
const maxRating = d3.max(booksForShelf.flat(), d => d.rating_score);
const heightScale = d3.scaleLinear().domain([minRating, maxRating])
.range([minHeight, maxHeight])
const minRatingAll = d3.min(data, d => d.rating_score);
const maxRatingAll = d3.max(data, d => d.rating_score);
const bookLightness = d3.scaleLinear().domain([minRatingAll, maxRatingAll])
.range([1.5, 0.1])
// add books to the shelf
let shelves = svg.selectAll("shelf")
.data(genreRatingsArr)
.join("g")
.attr("class", "shelf")
.attr("transform", (d, i) => `translate(0, ${110 + i * shelfHeight})`);
let rectangles = shelves.selectAll("rect")
.data(d => shelfMap.get(d[0]))
.join("rect")
.attr("x", (d, i) => 210 + i * (bookWidth + spaceBetweenBooks))
.attr("y", d => shelfHeight - 20 - heightScale(d.rating_score))
.attr("width", bookWidth)
.attr("height", d => heightScale(d.rating_score))
.attr("fill", d => {
let bookColor = d3.hsl(genreScale(d.top_genre));
bookColor.l = bookLightness(d.rating_score);
return bookColor;
})
.attr("stroke", "black")
.attr("stroke-width", 0.3);
// Add circles based on the condition
shelves.selectAll("circle") // Select circles within shelves
.data(d => shelfMap.get(d[0]))
.join("circle")
.attr("cx", (d, i) => 210 + i * (bookWidth + spaceBetweenBooks) + bookWidth / 2)
.attr("cy", d => shelfHeight - 25)
.attr("r", 3)
.attr("stroke", "black")
.attr("stroke-width", 0.3)
.attr("fill", "gold")
.style("visibility", d => {
return d.awarded
? "visible"
: "hidden";
});
let shelfposition = 205;
genreRatingsArr.forEach(genre => {
addText(genre[0], shelfposition);
shelfposition += 100;
});
let yearposition = 130;
let firstYears = []
let lastYears = []
shelfMap.forEach(genre => {
firstYears.push(genre[0]['publication_date'].getFullYear().toString())
lastYears.push(genre[49]['publication_date'].getFullYear().toString())
})
for (let i = 0; i < 5; i++) {
addYear(firstYears[i], lastYears[i], yearposition);
yearposition += 100;
}
// created tan label when mouse hovers over book
const label = createHoverLabel(
svg.append("g").style("visibility", "hidden"),
uniqueBooks,
awards_books);
// mouseover
rectangles.on("mouseover", function (event) {
let book = d3.select(this).datum();
d3.select(this)
.transition().duration(200)
.attr("stroke", "black")
.attr("stroke-width", 3);
label.select("#labelTitle").text(`Title: ${textCutoff(book.title, 30)}`);
label.select("#labelAuthors").text(`Author: ${book.authors}`);
label.select("#labelGenre").text(`Genre: ${book.top_genre}`);
label.select("#labelRating").text(`Rating: ${book.rating_score}`);
label.select("#labelXVar").text(`Publication Year: ${parseTime(book.publication_date, 'year')}`);
if (book.awarded) {
label.select("#labelAward").style('visibility', 'visible');
} else {
label.select("#labelAward").style('visibility', 'hidden');
}
label.style("visibility", "visible");
});
// label follows mouse
rectangles.on("mousemove", function (event) {
const [mouseX, mouseY] = d3.pointer(event, svg.node());
// let mouseXTrans
if (mouseX > width / 2) {
label.attr("transform", `translate(${mouseX - 275}, ${mouseY - 90})`);
} else {
label.attr("transform", `translate(${mouseX + 25}, ${mouseY - 90})`);
}
});
// mouseout
rectangles.on("mouseout", function (event) {
let book = d3.select(this).datum();
d3.select(this)
.transition().duration(200)
.attr("stroke", "black")
.attr("stroke-width", 0.3);
label.select("#labelAward").style('visibility', 'hidden');
label.style("visibility", "hidden");
});
// ----- SCATTERPLOTS -----
const plots = ['num_pages', 'publication_date', 'price', 'number_of_awards'];
plt_text = d3.select("#observations");
// add options to the dropdown
d3.select("#dropdown")
.selectAll('myOptions')
.data(plots)
.enter()
.append('option')
.text(d => formatLabel(d, 'label')) // text showed in the menu
.attr("value", d => d); // value returned by the button
plt_text.text(plot_observations['num_pages'])
plot_chartArea = createScatterplot(uniqueBooks, awards_books, 'num_pages', d3.scaleLinear(), 'rating_score', genreScale);
// Listen to the dropdown
d3.select("#dropdown").on("change", function (d) {
selected = this.value;
plt_text.text(plot_observations[selected]);
plot_chartArea = updateChart(selected, uniqueBooks, awards_books, genreScale);
addButtonAction(genres, genreScale, [plot_chartArea]);
})
// is a list in case we want more charts at the same time
const chartAreas = [plot_chartArea];
addButtonAction(genres, genreScale, chartAreas);
}
function addButtonAction(genres, genreScale, chartAreas) {
// // legend buttons
genres.forEach(genre => {
const g = genre.replace(' ', '_');
d3.select('#' + g)
.style("background-color", genreScale(genre))
.on("click", () => {
// console.log(genre);
chartAreas.forEach(c => {
c.selectAll("circle." + g)
// .transition().duration(1000)
.style("opacity", 0.4)
.style("visibility", "visible");
c.selectAll("circle:not(." + g + ")")
// .transition().duration(1000)
.style("visibility", "hidden");
});
});
})
d3.select('#All_Genres')
.on("click", () => {
// console.log("Clear");
chartAreas.forEach(c => {
c.selectAll("circle")
// .transition().duration(400)
.style("opacity", 0.4)
.style("visibility", "visible");
});
});
}
function updateChart(selected, uniqueBooks, awards_books, genreScale) {
const svg = d3.select('#scatterplot');
svg.selectAll("*").remove();
let chartArea = null;
if (selected == 'num_pages') {
chartArea = createScatterplot(uniqueBooks, awards_books, 'num_pages', d3.scaleLinear(), 'rating_score', genreScale);
}
else if (selected == 'publication_date') {
chartArea = createScatterplot(uniqueBooks, awards_books, 'publication_date', d3.scaleTime(), 'rating_score', genreScale);
}
else if (selected == 'price') {
chartArea = createScatterplot(uniqueBooks, awards_books, 'price', d3.scaleLinear(), 'rating_score', genreScale);
}
else {
chartArea = createScatterplot(awards_books, awards_books, 'number_of_awards', d3.scaleLog(), 'rating', genreScale);
}
return chartArea;
}
function createScatterplot(books, awards_books, x_var, x_scale_func, y_var, genreScale) {
// General dimensions of every scatterplot are the same
const svg = d3.select('#scatterplot');
const width = svg.attr('width');
const height = svg.attr('height');
const margins = { top: 50, right: 30, bottom: 60, left: 60 };
const chartWidth = width - margins.left - margins.right;
const chartHeight = height - margins.top - margins.bottom;
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("fill", "#fcebe3");
let chartArea = svg.append('g')
.attr('transform', `translate(${margins.left},${margins.top})`);
svg.append("text")
.attr("class", "title")
.attr("text-anchor", "middle")
.attr("x", chartWidth / 2 + margins.left)
.attr("y", 30)
.text(formatLabel(y_var, "title") + " vs. " + formatLabel(x_var, "title"))
.style("font-size", 18)
.style("font-weight", "bold");
// create scales
const xExtent = d3.extent(books, d => d[x_var]);
const xScale = x_scale_func.domain(xExtent).range([0, chartWidth]);
const yExtent = d3.extent(books, d => d[y_var]);
const yScale = d3.scaleLinear().domain(yExtent).range([chartHeight, 0]);
let leftGridlines = d3.axisLeft(yScale)
.tickSize(-chartWidth - 10)
.tickFormat('');
svg.append('g')
.attr('class', 'y gridlines')
.attr('transform', `translate(${margins.left},${margins.top})`)
.call(leftGridlines);
let bottomGridlines = d3.axisBottom(xScale)
.tickSize(-chartHeight - 10)
.tickFormat('');
svg.append('g')
.attr('class', 'x gridlines')
.attr('transform', `translate(${margins.left},${chartHeight + margins.top})`)
.call(bottomGridlines);
let leftAxis = d3.axisLeft(yScale);
svg.append('g')
.attr('class', 'y axis')
.attr('transform', `translate(${margins.left},${margins.top})`)
.call(leftAxis);
let bottomAxis = d3.axisBottom(xScale);
svg.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(${margins.left},${chartHeight + margins.top})`)
.call(bottomAxis);
// adding axis titles
svg.append("text")
.attr("class", "y label")
.attr("text-anchor", "middle")
.attr("x", -chartHeight / 2 - margins.top)
.attr("y", 25)
.attr("transform", "rotate(-90)")
.text(formatLabel(y_var, "axis"));
svg.append("text")
.attr("class", "x label")
.attr("text-anchor", "middle")
.attr("x", chartWidth / 2 + margins.left)
.attr("y", height - 20)
.text(formatLabel(x_var, "axis"));
// Zoom
let viewport = chartArea.append("g")
let circles = viewport.selectAll("circle")
.data(books)
.join("circle")
.attr("id", d => d['title'].replaceAll(' ', '_'))
.attr("class", d => d['top_genre'].replace(' ', '_'))
.attr("cx", d => xScale(d[x_var]))
.attr("cy", d => yScale(d[y_var]))
.attr("r", 5)
.style("fill", d => genreScale(d['top_genre']))
.style("opacity", 0.4);
chartArea.attr("clip-path", "url(#chartClip)");
var plotZoom = d3.zoom()
.scaleExtent([0.5, 20])
.on("zoom", plotZoomed);
svg.call(plotZoom)
svg.append("defs")
.lower()
.append("clipPath")
.attr("id", "chartClip")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", chartWidth)
.attr("height", chartHeight);
let zoomFactor = 1
function plotZoomed(event) {
viewport.attr("transform", event.transform);
leftAxis.scale(event.transform.rescaleX(yScale));
bottomAxis.scale(event.transform.rescaleX(xScale));
leftGridlines.scale(event.transform.rescaleY(yScale));
bottomGridlines.scale(event.transform.rescaleX(xScale));
svg.select("g.y.axis").call(leftAxis)
svg.select("g.x.axis").call(bottomAxis)
svg.select("g.y.gridlines").call(leftGridlines)
svg.select("g.x.gridlines").call(bottomGridlines)
zoomFactor = event.transform.k
viewport.selectAll("circle")
.attr("r", 5 / zoomFactor)
}
chartArea.raise();
// add label when hovering over circle
const label = createHoverLabel(
svg.append("g").style("visibility", "hidden"),
books,
awards_books);
circles.on("mouseover", function (event) {
let circle = d3.select(this);
let book = circle.datum();
let title = book['title'];
let authors = book['authors'];
let genre = book['top_genre'];
let xVarFormatted = formatLabel(x_var, 'label');
let xVarVal = book[x_var];
if (x_var == 'publication_date') {
xVarVal = parseTime(xVarVal, 'str');
} else if (x_var == 'price') {
xVarVal = "$" + xVarVal;
}
// let isbn = book['isbn']; // used as id for each circle
circle_x = circle.attr('cx');
circle_y = circle.attr('cy');
circle.raise()
.transition().duration(200)
.attr("r", 8 / zoomFactor)
.attr("stroke-width", 3 / zoomFactor)
.attr("stroke", d => darken(genreScale(d['top_genre']), 30))
.style("opacity", 1)
.style("fill", d => darken(genreScale(d['top_genre']), 10));
label.select("#labelTitle").text(`Title: ${textCutoff(book['title'], 30)}`);
label.select("#labelAuthors").text(`Author: ${textCutoff(book['authors'], 35)}`);
label.select("#labelGenre").text(`Genre: ${book['top_genre']}`);
label.select("#labelRating").text(`Rating: ${book['rating_score']}`);
label.select("#labelXVar").text(`${xVarFormatted}: ${xVarVal}`);
let awarded = false
if (x_var == 'number_of_awards') {
if (book['num_of_awards'] != 0) {
awarded = true
}
} else {
if (book['awarded']) {
awarded = true
}
}
if (awarded) {
label.select("#labelAward").style('visibility', 'visible');
} else {
label.select("#labelAward").style('visibility', 'hidden');
}
label.style("visibility", "visible");
const [mouseX, mouseY] = d3.pointer(event, svg.node());
// let mouseXTrans
// top right of chart
if (mouseX > chartWidth / 2 + margins.left && mouseY < chartHeight / 2 + margins.bottom) {
label.attr("transform", `translate(${mouseX - 275}, ${mouseY - 5})`);
}
// top left of chart
else if (mouseX < chartWidth / 2 + margins.left && mouseY < chartHeight / 2 + margins.bottom) {
label.attr("transform", `translate(${mouseX + 25}, ${mouseY - 5})`);
}
// bottom right of chart
else if (mouseX > chartWidth / 2 + margins.left && mouseY > chartHeight / 2 + margins.bottom) {
label.attr("transform", `translate(${mouseX - 275}, ${mouseY - 110})`);
}
// bottom left of chart
else {
label.attr("transform", `translate(${mouseX + 25}, ${mouseY - 110})`);
}
});
circles.on("mouseout", function () {
let circle = d3.select(this);