-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.html
253 lines (220 loc) · 7.3 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
<!DOCTYPE html>
<html>
<head>
<title>Game of Thrones: Word Count Per House</title>
<meta charset="UTF-8">
<meta name="description" content="Game of Thrones: Word Count Per House">
<meta name="author" content="Jeffrey Lancaster">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../style.css">
</head>
<body>
<svg></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
/* HELPFUL FUNCTIONS */
// to convert scene start/end times into seconds
function sec(timeString){
var sec = 0;
if (timeString.length == 0) return sec;
var splitArray = timeString.split(":");
sec = 3600*parseFloat(splitArray[0])+60*parseFloat(splitArray[1])+parseFloat(splitArray[2]);
return sec;
}
// to convert seconds into hh:mm:ss
function secondsToHMS(d) {
var date = new Date(null);
date.setSeconds(d); // specify value for SECONDS here
return date.toISOString().substr(11, 8);
}
// to dedpulicate an array
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
// to add commas to numbers
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var config = {
"title":"Word Count Per House",
"width":960,
"height":1000,
"margin":{
"top": 10,
"right": 40,
"bottom": 10,
"left": 120
},
"legendOffset": {
"x":20,
"y":50
},
"barHeight": 20
}
/* IMPORT DATA */
d3.queue()
.defer(d3.json, '../data/wordcount.json')
.defer(d3.json, '../data/characters-groups.json')
.await(ready);
function ready(error, w, g) {
if (error) throw error;
console.log("now that the files are loaded... do magic.");
/* CONFIG SETUP */
d3.select("svg")
.attr("width", config.width)
.attr("height", config.height)
/* END CONFIG SETUP */
// put all lines in one array
var words = w.count.reduce(function(acc, val, ind){
var word = val.text.reduce(function(a, v, i){
var c = Object.assign({}, v, {"seasonNum":val.seasonNum, "episodeNum":val.episodeNum});
return a.concat(c);
}, []);
return [...acc, ...word];
}, []);
// put all seasons in an array
var seasons = words.reduce(function(acc, val, ind){
return [...acc, val.seasonNum];
}, [])
.filter(onlyUnique);
// then put that array into an object with 0 count
var seasonsObj = seasons.reduce(function(acc, val, ind){
var obj = {};
obj[val] = 0;
return Object.assign(acc, obj);
}, {});
// put all characters in one array, make object to count character words
var characters = words.map(function(val, ind){
return val.name
})
.filter(onlyUnique)
.map(function(cur, ind){
return Object.assign({}, {"name": cur}, seasonsObj);
});
// go through lines and add word count values to characters' counts
words.forEach(function(val, ind){
var index = characters.findIndex(function(element){
return element.name == val.name;
});
characters[index][val.seasonNum] += val.count;
})
// remove the "Include" group
g.groups.pop();
// put remaining groups in an array
var groups = g.groups.reduce(function(acc, val, ind){
return [...acc, val.name]
}, [])
.filter(onlyUnique)
.map(function(cur, ind){
var groups = ["Lannister", "Stark", "Baratheon", "Targaryen", "Tyrell", "Greyjoy", "Martell", "Frey", "Tully"];
var alt = (groups.indexOf(cur) > -1) ? `House ${cur}` : `The ${cur}`;
return Object.assign({}, {"name": cur, "nameAlt": alt}, seasonsObj);
});
// go through characters and add season value to houses' counts
g.groups.forEach(function(val, ind){
val.characters.forEach(function(v, i){
var characterIndex = characters.findIndex(function(element){
return element.name == v;
});
var houseIndex = groups.findIndex(function(element){
return element.name == val.name;
});
if(characterIndex > -1){
seasons.forEach(function(value, index){
groups[houseIndex][value] += characters[characterIndex][value]
})
}
})
})
// build the visualization
var data = groups;
var barHeight = config.barHeight;
var svg = d3.select("svg"),
margin = config.margin,
width = +svg.attr("width") - margin.left - margin.right,
height = barHeight*data.length + margin.top + margin.bottom,
g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.attr("height", height);
var y = d3.scaleBand()
.rangeRound([0, height])
.paddingInner(0.15)
.align(0.1);
var x = d3.scaleLinear()
.rangeRound([0, width]);
var z = d3.scaleOrdinal() // or d3.schemeCategory20c between () and no .range
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00", "#FEC574"]);
var keys = d3.keys(data[0]).slice(0, Math.max(...seasons));
for (i=0; i<data.length; i++){
var t=0;
for(j=0; j<keys.length; j++){
t += data[i][keys[j]];
}
data[i].total = t;
}
data.sort(function(a, b) { return a.total - b.total; }).reverse();
y.domain(data.map(function(d) { return d.name; }));
x.domain([0, d3.max(data, function(d) { return d.total; })]).nice();
z.domain(keys);
g.append("g")
.selectAll("g")
.data(d3.stack().keys(keys)(data))
.enter().append("g")
.attr("fill", function(d) { return z(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("y", function(d) { return y(d.data.name); })
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("height", y.bandwidth())
.append("svg:title")
.text(function(d){
var name = d.data.nameAlt;
var season = d3.select(this.parentNode.parentNode).datum().key;
var diff = d[1]-d[0];
var word = (diff == 1) ? "word" : "words";
return `${name} spoke ${numberWithCommas(diff)} ${word} in Season ${season}`;
});
g.append("g")
.attr("class", "axis")
.attr("transform", "translate(0,0)")
.call(d3.axisLeft(y)
.tickFormat(function(d){
var groups = ["Lannister", "Stark", "Baratheon", "Targaryen", "Tyrell", "Greyjoy", "Martell", "Frey", "Tully"];
var alt = (groups.indexOf(d) > -1) ? `House ${d}` : `The ${d}`;
return alt;
})
);
g.selectAll(".axis")
.selectAll(".tick")
.data(data)
.append("text")
.attr("class", "timestamp")
.attr("dy", "0.35em")
.attr("dx", function(d){ return x(d.total) + 5; })
.attr("text-anchor", "start")
.text(function(d){ return numberWithCommas(d.total); });
var legend = g.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("text-anchor", "end")
.attr("transform", function(d, i) {return `translate(${config.legendOffset.x}, ${config.legendOffset.y})`})
.selectAll("g")
.data(keys.slice())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 19)
.attr("width", 19)
.attr("height", 19)
.attr("fill", z);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9.5)
.attr("dy", "0.32em")
.text(function(d) { return `Season ${d}`; });
};
</script>
</body>
</html>