-
Notifications
You must be signed in to change notification settings - Fork 2
/
visualization.html
1016 lines (885 loc) · 40.3 KB
/
visualization.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>
<meta charset="utf-8">
<title>Book Recommendation</title>
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://cdn.jsdelivr.net/gh/holtzy/D3-graph-gallery@master/LIB/d3.layout.cloud.js"></script>
<script type="text/javascript" src="lib/d3.v5.min.js"></script>
<script type="text/javascript" src="/eel.js"></script>
<style>
.recommendation {
/*margin-top: 10px;*/
width: 100%;
text-align: center;
}
.row {
display: flex;
}
.column_left {
flex: 70%;
padding: 15px;
margin: 20px;
height: 40vw;
font-family: American Typewriter;
font-size: 20px;
}
.column_right {
flex: 30%;
padding: 15px;
margin: 20px;
height: 40vw;
font-family: American Typewriter;
font-size: 20px;
}
.rate {
float: left;
height: 46px;
padding: 0 10px;
}
.rate:not(:checked)>input {
position: absolute;
top: -9999px;
}
.rate:not(:checked)>label {
float: right;
width: 1em;
overflow: hidden;
white-space: nowrap;
cursor: pointer;
font-size: 30px;
color: #ccc;
}
.rate:not(:checked)>label:before {
content: '★ ';
}
.rate>input:checked~label {
color: #ffc700;
}
.rate:not(:checked)>label:hover,
.rate:not(:checked)>label:hover~label {
color: #deb217;
}
.rate>input:checked+label:hover,
.rate>input:checked+label:hover~label,
.rate>input:checked~label:hover,
.rate>input:checked~label:hover~label,
.rate>label:hover~input:checked~label {
color: #c59b08;
}
.category {
width: 100%;
text-align: center;
}
</style>
</head>
<body style="background: #faf1cd">
<div style="font-family: American Typewriter; font-size: 40px; text-align: left; margin: 15px;">
Recommendation Result:
<span style="text-align: right;">
<a href='welcome.html'><img src="icon/home.png" alt="Home" width="50" height="50"></a>
</span>
</div>
<div class="recommendation">
<!-- <div id=""></div> -->
<div class="category_div" id="category_div">
<!-- <label>Select Category: </label> -->
<!-- <select id="categoryDropdown"></select> -->
<!-- <div class="book" id="book"></div> -->
</div>
<div class="row">
<!--Put visualization in this div-->
<div class="column_left" id="data_vis"></div>
<!--Put book's information in this div-->
<div class="column_right" id="book_info"></div>
</div>
</div>
<table>
<tr>
<td style="font-family: American Typewriter; font-size: 15px; margin: 5px;">Rate this recommendation:</td>
<td class="rate">
<input type="radio" id="star5" name="rate" value="5" />
<label for="star5" title="text">5 stars</label>
<input type="radio" id="star4" name="rate" value="4" />
<label for="star4" title="text">4 stars</label>
<input type="radio" id="star3" name="rate" value="3" />
<label for="star3" title="text">3 stars</label>
<input type="radio" id="star2" name="rate" value="2" />
<label for="star2" title="text">2 stars</label>
<input type="radio" id="star1" name="rate" value="1" />
<label for="star1" title="text">1 star</label>
</td>
<td style="font-family: American Typewriter; font-size: 15px; margin: 10px;">Comments: </td>
<td>
<input type='text' id='comment'>
<input id="submit" type="submit" class="btn" onclick="submit();">
</td>
</tr>
</table>
<script>
const params = new URLSearchParams(window.location.search)
var method = params.get("method");
if (method == "age") {
//age recommendation and visualization
var age_group = params.get("age");
const width = 960;
const height = 500;
const margin = 5;
const padding = 5;
const adj = 100;
var svg = d3.select(".column_left").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "-"
+ adj + " -"
+ adj + " "
+ (width + adj * 3) + " "
+ (height + adj * 3))
.style("padding", padding)
.style("margin", margin)
.classed("svg-content", true);
d3.dsv(",", "data/merged_Agedata_final.csv").then(function (data) {
// console.log("data", data)
// console.log(data[1].Age)
var ageClass = {};
data.forEach(function (d) {
var ageGroup;
var idGroup;
if (d.Age != "") {
if (d.Age <= 10) {
idGroup = 0;
ageGroup = '0-10';
} else if (d.Age > 10 && d.Age <= 20) {
idGroup = 1;
ageGroup = '10-20';
} else if (d.Age > 20 && d.Age <= 30) {
idGroup = 2;
ageGroup = '20-30';
} else if (d.Age > 30 && d.Age <= 40) {
idGroup = 3;
ageGroup = '30-40';
} else if (d.Age > 40 && d.Age <= 50) {
idGroup = 4;
ageGroup = '40-50';
} else if (d.Age > 50 && d.Age <= 60) {
idGroup = 5;
ageGroup = '50-60';
} else if (d.Age > 60 && d.Age <= 70) {
idGroup = 6;
ageGroup = '60-70';
} else if (d.Age > 70 && d.Age <= 80) {
idGroup = 7;
ageGroup = '70-80';
} else if (d.Age > 80 && d.Age <= 90) {
idGroup = 8;
ageGroup = '80-90';
} else if (d.Age > 90) {
idGroup = 9;
ageGroup = '>90';
}
}
if (!ageClass[idGroup]) {
ageClass[idGroup] = [];
}
if (d.Age != " ") {
ageClass[idGroup].push({ ageGroup: ageGroup, age: d.Age, ISBN: d.ISBN, Book: d["Book-Title"], Pic: d["Image-URL-M"] });
}
});
//console.log("ageClass", ageClass)
var AgeCountData = [];
var sum = 0;
for (const [key, value] of Object.entries(ageClass)) {
if (key != "undefined") {
var groupBook = [];
var maxCount = 0;
for (var i = 0; i < value.length; i++) {
var item = value[i];
if (item.ISBN != "NULL") {
if (!groupBook[item.ISBN]) {
groupBook[item.ISBN] = [];
}
groupBook[item.ISBN].push({ ISBM: item.ISBN, Book: item.Book, Pic: item.Pic });
if (maxCount < groupBook[item.ISBN].length) {
maxCount = groupBook[item.ISBN].length;
maxItem = item.ISBN
maxBook = item.Book
maxPic = item.Pic
}
}
}
// console.log("groupBook", groupBook)
// console.log("popularBook", maxCount, maxItem, maxBook, maxPic)
AgeCountData.push({ ageId: key, age: value[0].ageGroup, count: value.length, popBook: maxBook, popPic: maxPic })
sum += value.length;
}
}
var xScale = d3.scaleBand().range([0, width]).padding(0.4),
yScale = d3.scaleLinear().range([height, 0]);
xScale.domain(AgeCountData.map(function (d) { return d.age; }));
yScale.domain([0, d3.max(AgeCountData, function (d) { return d.count; })]);
var xAxis = d3.axisBottom().scale(xScale);
var yAxis = d3.axisLeft().scale(yScale)
.tickFormat(function (d) {
return d;
}).ticks(5);
svg.append("text")
.attr("y", -adj * 0.5)
.attr("x", width / 2 - adj * 1.6)
.attr("font-size", "30px")
.text("Age-based Recommendation")
svg.append("g")
.attr("id", "x-axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("id", "y-axis")
.call(yAxis);
svg.append("text")
.attr("id", "x-axis label")
.attr("y", height + 50)
.attr("x", width / 2)
.text("Age");
svg.append("text")
.attr("id", "y-axis label")
.attr("transform", "rotate(-90)")
.attr("dy", "1em")
.attr("y", -adj * 0.8)
.attr("x", -adj * 3)
.text("Population");
svg.append('g')
.attr('class', 'grid')
.style("color", "Gainsboro")
.attr("stroke-width", "1")
.call(d3.axisLeft()
.scale(yScale)
.tickSize(-width, 0, 0)
.tickFormat(''))
// right column
var showAgePopBooks = d3.select(".column_right")
showAgePopBooks.append('div')
.append('p')
.text("Let's see what's the hottest book in your age group...")
const tooltip = d3.select(".column_left").append('div')
.attr('class', 'tooltip')
.style('opacity', 0);
const tooltipPic = d3.select(".column_left").append('div')
.attr('class', 'tooltipPic')
.style('opacity', 0);
var bar = svg.selectAll(".bar")
.data(AgeCountData)
.enter().append("rect")
.attr("class", "bar")
.style("fill", "LightSteelBlue")
.on("mouseover", onMouseOver)
.on("mouseout", onMouseOut)
.attr("x", function (d) { return xScale(d.age); })
.attr("y", function (d) { return yScale(d.count); })
.attr("width", xScale.bandwidth())
.attr("height", function (d) { return height - yScale(d.count); });
//mouseover event handler function
function onMouseOver(d, i) {
d3.select(this).attr('class', 'highlight');
d3.select(this)
.transition() // adds animation
.duration(300)
.style("fill", "LightBlue")
.attr('width', xScale.bandwidth() + 3)
.attr("y", function (d) { return yScale(d.count) - 10; })
.attr("height", function (d) { return height - yScale(d.count) + 10; });
svg.append("text")
.attr('class', 'val')
.attr('x', function () {
return xScale(d.age) + 15;
})
.attr('y', function () {
return yScale(d.count) - 15;
})
.text(function () {
return (d3.format(".2s")([d.count] / sum * 100)) + "%"; // Value of the text
});
var string = "<img src=" + d.popPic + "/>";
// https://codepen.io/jackdbd/pen/NAEdBG
tooltip.transition().duration(200)
.style('opacity', 0.9);
tooltip.html(`Title: <span>${d.popBook}</span>`)
.style('left', `${(d3.event.layerX + 13)}px`)
.style('top', `${(d3.event.layerY - 28)}px`);
// image in tooltip
tooltipPic.transition().duration(200)
.style('opacity', 0.9);
tooltipPic.html(string)
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY - 8.4 + "px");
}
//mouseout event handler function
function onMouseOut(d, i) {
// use the text label class to remove label on mouseout
d3.select(this).attr('class', 'bar');
d3.select(this)
.transition() // adds animation
.duration(300)
.style("fill", "LightSteelBlue")
.attr('width', xScale.bandwidth())
.attr("y", function (d) { return yScale(d.count); })
.attr("height", function (d) { return height - yScale(d.count); });
d3.selectAll('.val')
.remove()
tooltip.transition().duration(200)
.style('opacity', 0)
tooltipPic.transition().duration(200)
.style('opacity', 0)
}
});
}
else if (method == "region") {
//region recommendation and visualization
var region = params.get("region");
// Define margin and dimensions for svg
var margin = { top: -40, right: 200, bottom: 30, left: 100 };
var ww = 1400;
var hh = 700;
var w = ww - margin.left - margin.right;
var h = hh - margin.top - margin.bottom;
var book;
// Create svg
var showFiveBooksDiv = d3.select(".column_right")
.append('div')
.append('p')
.text("Guess you like...");
// d3.select(".column_left")
// .append('div')
// .append('p')
// .text("See what other country's people like");
var svg = d3.select(".column_left")
.append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.style("background-color", "#5d757e")
.style("padding", 0)
.style("margin", -15)
.attr("viewBox", "0 0 " + w + " " + h)
.classed("svg-content", true);
var countryPaths = svg.append('g')
.attr('id', 'countries');
// Define projection & path required for world map
var projection = d3.geoNaturalEarth1()
.translate([w / 2, h / 2])
.scale(215)
.center([15, 0]);
var path = d3.geoPath()
.projection(projection);
// Load data
var worldmap = d3.json('data/world_countries.json', function (err, jsondata) {
// console.log(jsondata);
});
var bookRegionWeight = d3.csv('data/region_score_sort.csv');
Promise.all([
// Read files
worldmap,
bookRegionWeight
])
.then(function (data) {
// Call ready()
ready(0, data[0], data[1]);
});
// Preprocess data
function ready(error, world, b) {
// console.log(book);
book = b;
var selectedCountry = region;
var cnt = 0;
var fiveBooks = [];
for (var i = 0; i < book.length; ++i) {
if (book[i]['country'] === selectedCountry) {
fiveBooks.push(book[i]);
cnt = cnt + 1;
if (cnt >= 5) break;
}
}
// Call createMapAndLegend()
createMapAndLegend(world, fiveBooks, selectedCountry);
}
function searchFiveBooks(selected) {
var selectedCountry = selected.toLowerCase();
var cnt = 0;
var fiveBooks = [];
for (var i = 0; i < book.length; ++i) {
if (book[i]['country'] === selectedCountry) {
fiveBooks.push(book[i]);
cnt = cnt + 1;
if (cnt >= 5) break;
}
}
return fiveBooks;
}
// Create a world map and recommend books for a selected country
function createMapAndLegend(world, fiveBooks, selectedCountry) {
// console.log(world);
// Define a tooltip
var tooltip2;
// Draw the boundaries of countries
countryPaths.selectAll("path")
.data(world.features)
.enter()
.append("path")
.attr("stroke", "#a09daf")
.attr("class", "countries")
.attr("d", path)
.attr('fill', function (d) {
var countryName = d.properties.name.toLowerCase();
if (countryName === region.toLowerCase())
return '#ace8e1';
return '#2E3E3C';
})
.on('mouseover', function (d) {
// Change color of a country
d3.select(this)
.attr('fill', '#61716f');
// Everytime mouseover, recreate a tooltip
var countryName = d.properties.name;
tooltip2 = d3.select(".column_left")
.append("div")
.attr('id', 'tooltip')
.style("position", "absolute")
.style("visibility", "hidden")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px");
// Show 5 books on the tooltip
var fb = searchFiveBooks(countryName);
d3.select('#tooltip')
.append('text')
.html('<p>' + countryName + '</p>');
if (fb.length > 0) {
d3.select('#tooltip')
.selectAll('img')
.data(fb)
.enter()
.append('img')
.attr('src', function (d, i) { return fb[i]['img_s']; });
}
else {
d3.select('#tooltip')
.append('text')
.html('<p>No books!</p>');
}
return tooltip2.style("visibility", "visible");
})
.on('mousemove', function () {
return tooltip2.style("top", (event.pageY - 0) + "px").style("left", (event.pageX - 300) + "px");
})
.on('mouseout', function (d) {
// Change color of a country
var countryName = d.properties.name.toLowerCase();
if (countryName === region.toLowerCase())
d3.select(this)
.attr('fill', '#ace8e1');
else {
d3.select(this)
.attr('fill', '#2E3E3C');
}
// Everytime mouseout, delete tooltip
d3.select('#tooltip').remove();
// return tooltip2.style("visibility", "hidden");
});
showFiveBooksDiv.append('div')
.append('img')
.attr("src", fiveBooks[0]['img_l']);
showFiveBooksDiv.append('text')
.html('Book Name: ' + fiveBooks[0]['book_title'] + '</br>' +
'ISBN: ' + fiveBooks[0]['isbn'] + '</br>');
} // end of createMapAndLegend()
}
else if (method == "category") {
//category recommendation and visualization
var category = params.get("category");
var catDiv = d3.select('.category_div');
var selectTag = catDiv.append('select');
var showFiveBooksDiv = catDiv.append('div')
.attr('class', "book")
.attr('id', "book");
// Define a tooltip
var tooltip1;
var book_cat_data;
var greenCode = '#69b3a2';
var lightGreenCode = '#3d796b';
d3.dsv(",", "data/cat_score_sort.csv", function (d) {
// console.log(d);
return d;
})
.then(function (book) {
console.log(book);
book_cat_data = book;
var selectedCategory = category;
var cnt = 0;
var fiveBooks = [];
for (var i = 0; i < book.length; ++i) {
if (book[i]['Category'] == selectedCategory) {
fiveBooks.push(book[i]);
cnt = cnt + 1;
if (cnt >= 5) break;
}
}
console.log(selectedCategory);
console.log(fiveBooks);
var unique_categories = [...new Set(book.map(item => item.Category))];
unique_categories = unique_categories.sort()
// Append options
selectTag.selectAll("option")
.data(unique_categories)
.enter()
.append("option")
.attr("value", function (d) { return d; })
.append("text")
.text(function (d) { return d; })
.property("selected", function (d) {
return d === selectedCategory;
});
selectTag.on("change", function (d) {
selectedCategory = d3.select(this).property("value");
d3.select('.column_right').selectAll("img").remove();
d3.select('.column_right').selectAll("text").remove();
var cnt = 0;
fiveBooks = [];
for (var i = 0; i < book.length; ++i) {
if (book[i]['Category'] == selectedCategory) {
fiveBooks.push(book[i]);
cnt = cnt + 1;
if (cnt >= 5) break;
}
}
createMapAndLegend(fiveBooks, selectedCategory)
});
createMapAndLegend(fiveBooks, selectedCategory);
function createMapAndLegend(fiveBooks, selectedCategory) {
d3.select('.column_right').append('div')
.append('img')
.attr("src", fiveBooks[0]['img_l']);
d3.select('.column_right').append('text')
.html('Book Name: ' + fiveBooks[0]['book_title'] + '</br>' +
'ISBN: ' + fiveBooks[0]['isbn'] + '</br>');
}
}); // end of then
// Bar chart for category
// Set the dimensions and margins of the graph
var margin = { top: 0, right: 0, bottom: 250, left: 40 },
width = 815 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// Set the ranges
var x = d3.scaleBand()
.range([0, width])
.padding(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
var svg = d3.select(".column_left")
.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 + ")"); // moves the 'group' element to the top left margin
// Load the data
d3.csv("data/cat_count_sort.csv").then(function(data) {
// Format the data
data.forEach(function(d) {
d.count = +d.count;
d.log_count = +d.log_count;
});
function searchFiveBooks(selected) {
var cnt = 0;
var fiveBooks = [];
for (var i = 0; i < book_cat_data.length; ++i) {
if (book_cat_data[i]['Category'] === selected) {
fiveBooks.push(book_cat_data[i]);
cnt = cnt + 1;
if (cnt >= 5) break;
}
}
return fiveBooks;
}
// Scale the range of the data in the domains
x.domain(data.map(function(d) { return d.Category; }));
y.domain([0, d3.max(data, function(d) { return d.log_count; })]);
// Append the rectangles for the bar chart
svg.selectAll(".mybar")
.data(data)
.enter()
.append("rect")
.attr("class", "mybar")
.attr("fill", greenCode)
.attr("x", function(d) { return x(d.Category); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.log_count); })
.attr("height", function(d) { return height - y(d.log_count); })
.on('mouseover', function (d) {
// Change color of a country
d3.select(this).attr('fill', lightGreenCode);
// Everytime mouseover, recreate a tooltip
var countryName = d.Category;
tooltip1 = d3.select(".column_left")
.append("div")
.attr('id', 'tooltip1')
.style("position", "absolute")
.style("visibility", "hidden")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "1px")
.style("border-radius", "5px")
.style("padding", "10px");
// Show 5 books on the tooltip
var fb = searchFiveBooks(countryName);
d3.select('#tooltip1')
.append('text')
.html('<p>' + countryName + '</p>');
if (fb.length > 0) {
d3.select('#tooltip1')
.selectAll('img')
.data(fb)
.enter()
.append('img')
.attr('src', function (d, i) { return fb[i]['img_s']; });
}
else {
d3.select('#tooltip1')
.append('text')
.html('<p>No books!</p>');
}
return tooltip1.style("visibility", "visible");
})
.on('mousemove', function () {
return tooltip1.style("top", (event.pageY - 200) + "px").style("left", (event.pageX - 0) + "px");
})
.on('mouseout', function (d) {
// Change color of a bar
d3.select(this).attr('fill', greenCode);
// Everytime mouseout, delete tooltip
d3.select('#tooltip1').remove();
});
// Add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-65)");
// Add the y Axis
svg.append("g")
.call(d3.axisLeft(y));
}); // end of then
}
else if (method == "book") {
//rating recommendation and visualization
var bookname = params.get("bookname");
const width = 960;
const height = 500;
const margin = 5;
const padding = 5;
const adj = 100;
var svg = d3.select(".column_left").append("svg")
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "-"
+ adj + " -"
+ adj + " "
+ (width + adj * 3) + " "
+ (height + adj * 3))
.style("padding", padding)
.style("margin", margin)
.classed("svg-content", true);
// console.log(bookname);
async function run() {
let recommendation = await eel.content_based_cf(bookname)();
console.log(recommendation)
if (recommendation == 1) {
// input book is not in the dataset
svg.append("text")
.attr("y", height / 2 - 20)
.attr("x", width / 2 - 270)
.attr("font-size", "40px")
.attr("dy", "0em")
.text("The book is not in the dataset.")
svg.append("text")
.attr("y", height / 2 - 20)
.attr("x", width / 2 - 270)
.attr("font-size", "40px")
.attr("dy", "2em")
.text("Please try another book.")
}
else if (recommendation == 2) {
// no recommendation : low rating
svg.append("text")
.attr("y", height / 2 - 20)
.attr("x", width / 2 - 300)
.attr("font-size", "40px")
.attr("dy", "0em")
.text("There is no reccomendation for this book.")
svg.append("text")
.attr("y", height / 2 - 20)
.attr("x", width / 2 - 300)
.attr("font-size", "40px")
.attr("dy", "2em")
.text("Please try another book.")
}
else {
// content-based cf
predicted_rating = recommendation[0]
predicted_book = recommendation[1]
predicted_url = recommendation[2]
console.log(predicted_rating);
console.log(predicted_book);
console.log(predicted_url);
barchart_data = []
for (i = 0; i < 5; i++) {
predicted_rating_percentage = predicted_rating[i] * 100
barchart_data.push({ book: predicted_book[i], rating: predicted_rating_percentage })
}
console.log(barchart_data)
// show the highest-rating recommendation
var showBooks = d3.select(".column_right");
showBooks.append('div')
.append('img')
.attr("src", predicted_url[0]);
showBooks.append('text')
.html('\nBook Name: ' + predicted_book[0] + '</br>')
var xScale = d3.scaleBand().range([0, width]).padding(0.4),
yScale = d3.scaleLinear().range([height, 0]);
xScale.domain(barchart_data.map(function (d) { return d.book; }));
yScale.domain([0, d3.max(barchart_data, function (d) { return d.rating; })]);
var xAxis = d3.axisBottom().scale(xScale);
var yAxis = d3.axisLeft().scale(yScale)
.tickFormat(function (d) {
return d;
}).ticks(5);
svg.append("text")
.attr("y", -adj * 0.5)
.attr("x", width / 2 - 250)
.attr("font-size", "40px")
.text("Book Name Recommendation")
svg.append("g")
.attr("id", "x-axis")
.attr("transform", "translate(0," + height + ")")
.transition()
.call(xAxis)
.on("end", function () {
d3.select(this)
.selectAll(".tick text")
.attr("font-size", "20px")
.attr("dy", "1.5em")
.call(wrap, xScale.bandwidth() * 1.5)
});
svg.append("g")
.attr("id", "y-axis")
.transition()
.call(yAxis)
.on("end", function () {
d3.select(this)
.selectAll(".tick text")
.attr("font-size", "20px")
});
svg.append("text")
.attr("id", "x-axis label")
.attr("y", height + 120)
.attr("x", width / 2 - 80)
.attr("font-size", "30px")
.text("Book Name");
svg.append("text")
.attr("id", "y-axis label")
.attr("transform", "rotate(-90)")
.attr("dy", "-1em")
.attr("y", -adj * 0.25)
.attr("x", -adj * 4)
.attr("font-size", "30px")
.text("Predicted rating");
var bar = svg.selectAll(".bar")
.data(barchart_data)
.enter().append("rect")
.attr("class", "bar")
.style("fill", "#ffc700")
.attr("x", function (d) { return xScale(d.book); })
.attr("y", function (d) { return yScale(d.rating); })
.attr("width", xScale.bandwidth())
.attr("height", function (d) { return height - yScale(d.rating); });
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
}
}
run();
}
else if (method == "twitter") {
var keyword = params.get("keyword");
var margin = { top: 10, right: 10, bottom: 10, left: 10 },
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var svg = d3.select("#data_vis").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 + ")");
var layout = d3.layout.cloud();
//console.log(myWords)
document.getElementById('book_info').innerHTML = "Loading...";
async function run() {
let results = await eel.twitter_wordcnt(keyword)();
bookname = results[0]
bookisbn = results[1]
bookimg = results[2]
myWords = results[3]
console.log(myWords);
document.getElementById('book_info').innerHTML = "";
var showBooks = d3.select(".column_right");
showBooks.append('div')
.append('img')
.attr("src", bookimg);
showBooks.append('text')
.html('Book Name: ' + bookname + '</br>' +
'ISBN: ' + bookisbn + '</br>')
layout.size([width, height])
.words(myWords.map(function (d) { return { text: d.word, size: d.size }; }))
.padding(12) //space between words
.rotate(function () { return ~~(Math.random() * 2) * 90; })
.fontSize(function (d) { return d.size; }) // font size of words
.on("end", draw);
layout.start();
}
run();
function draw(words) {
svg.append("g")
.attr("transform", "translate(" + layout.size()[0] / 2 + "," + layout.size()[1] / 2 + ")")
.selectAll("text")