-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrq_three.py
276 lines (230 loc) · 9.27 KB
/
rq_three.py
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
"""
KV Le
CSE 163 AG
Final Project
A script that has multiple functions that manipulate/visualize data about
My Anime List to answer my third research question for my final project.
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
distinct_colors = \
['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4',
'#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff',
'#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1',
'#000075', '#808080', '#ffffff']
def plot_yearly_studio_score(data, top_n=20):
"""Plots the average score per year for the top_n studios
Parameters
----------
data : DataFrame
Pandas DataFrame that contains anime show data
top_n: Integer
The amount of top studios that the plot will contain
Notes
-----
Visualization Type: Line Plot
File Path: plots/rq3_{top_n}studios_yearly_score.png
If the top_n value goes over the length of "distinct_colors", the palette
will be shifted back to the default, which has indistinct colors
Top_n is determined by the average scores of anime made with the studio
"""
info = data[["studio", "score", "aired_from_year"]].copy()
info["studio"] = info["studio"].str.split(", ")
info = info.explode("studio").groupby(["studio", "aired_from_year"]) \
.mean().sort_values("score", ascending=False).reset_index()
top_studios = info.groupby("studio").mean() \
.sort_values("score", ascending=False).iloc[:top_n]["score"]
info = info[info["studio"].isin(top_studios.index)]
palette = distinct_colors[:top_n] if top_n < len(distinct_colors) else None
fig, ax = plt.subplots()
fig.set_size_inches(15, 10)
sns.lineplot(x="aired_from_year", y="score", hue="studio",
palette=palette, data=info, ax=ax)
fig.suptitle(f"Average Yearly Score of the Top {top_n} Studios")
ax.set_xlabel("Year")
ax.set_ylabel("Score out of Ten")
ax.set_ylim(0, 10)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
fig.savefig(f"plots/rq3_{top_n}studios_yearly_score.png",
bbox_inches="tight")
plt.close(fig)
def plot_studio_averages(data):
"""Plots the average score for anime studios
Parameters
----------
data : DataFrame
Pandas DataFrame that contains anime show data
Notes
-----
Visualization Type: Bar Plot
File Path: plots/rq3_{top_n}studios_yearly_score.png
"""
info = data[["studio", "score"]].copy()
info["studio"] = info["studio"].str.split(", ")
info = info.explode("studio").groupby("studio").mean() \
.sort_values("score", ascending=False).reset_index()
fig, ax = plt.subplots()
fig.set_size_inches(15, 10)
sns.barplot(x="studio", y="score",
data=info.iloc[:25], ax=ax)
fig.suptitle("Top 25 Studio Scores")
ax.set_xlabel("Studios")
ax.set_ylabel("Score out of Ten")
ax.set_ylim(6, 9)
plt.xticks(rotation=45, ha="right")
fig.savefig("plots/rq3_best_studio_scores.png", bbox_inches="tight")
plt.close(fig)
fig, ax = plt.subplots()
fig.set_size_inches(15, 10)
sns.barplot(x="studio", y="score",
data=info.iloc[:-25:-1], ax=ax)
fig.suptitle("Worst 25 Studio Scores")
ax.set_xlabel("Studios")
ax.set_ylabel("Score out of Ten")
ax.set_ylim(2, 6)
plt.xticks(rotation=45, ha="right")
fig.savefig("plots/rq3_worst_studio_scores.png", bbox_inches="tight")
plt.close(fig)
def plot_genre_average(data, top_n=5, genres=None):
"""Plots the top and bottom 25 studio scores for the top_n genres
Parameters
----------
data : DataFrame
Pandas DataFrame that contains anime show data
top_n: Integer
The amount of top studios that the plot will contain
genres: List
List of genres that can override top_n
Notes
-----
Visualization Type: Line Plot
File Path: plots/rq3_{top_n}studios_yearly_score.png
If the top_n value goes over the length of "distinct_colors", the palette
will be shifted back to the default, which has indistinct colors
Top_n is determined by the average scores of genre
"""
info = data[["genre", "studio", "score"]].copy()
info["studio"] = info["studio"].str.split(", ")
info = info.explode("studio")
info["genre"] = info["genre"].str.split(", ")
info = info.explode("genre")
if genres:
top_genres = genres
else:
top_genres = \
info.groupby("genre").mean() \
.sort_values("score", ascending=False)
top_genres = \
top_genres.iloc[:(top_n if top_n else len(top_genres))].index
for genre in top_genres:
genre_info = info[info["genre"] == genre]
genre_info = genre_info.groupby("studio").mean()
genre_info = genre_info.sort_values("score", ascending=False) \
.reset_index()
fig, axs = plt.subplots(2)
fig.set_size_inches(16, 20)
axs[0].set_title(f"Top 25 {genre} Studios")
sns.barplot(x="studio", y="score",
data=genre_info.iloc[:25], ax=axs[0])
axs[0].set_xlabel("Studio")
axs[0].set_ylabel("Score out of Ten")
plt.setp(axs[0].get_xticklabels(), ha="right", rotation=45)
axs[1].set_title(f"Bottom 25 {genre} Studios")
sns.barplot(x="studio", y="score",
data=genre_info.iloc[:-25:-1], ax=axs[1])
axs[1].set_xlabel("Studio")
axs[1].set_ylabel("Score out of Ten")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
if top_n:
fig.savefig(f"plots/rq3_genre_{genre.lower()}_scores.png",
bbox_inches="tight")
else:
fig.savefig(f"plots/rq3_genres/rq3_{genre.lower()}_scores.png",
bbox_inches="tight")
plt.close(fig)
def plot_studio_amounts(data, name="studio_amounts"):
"""Plots the amount of anime made by each studio
Parameters
----------
data : DataFrame
Pandas DataFrame that contains anime show data
name : String
Determines name of the file
Notes
-----
Visualization Type: Bar Plot
File Path: plots/rq3_{name}.png
"""
studios = data["studio"].str.split(", ", expand=True).stack() \
.str.get_dummies().sum().sort_values(ascending=False).iloc[0:50]
fig, ax = plt.subplots()
fig.set_size_inches(15, 10)
fig.suptitle("Amount of Animes made by Studios")
sns.barplot(x=studios.index, y=studios.values, ax=ax)
ax.set_xlabel("Studios")
ax.set_ylabel("Amount of Anime")
plt.xticks(rotation=45, ha="right")
fig.savefig(f"plots/rq3_{name}.png", bbox_inches="tight")
plt.close(fig)
def plot_studio_count_yearly(data, top_n=10):
"""Plots the yearly count of the top_n studios
Parameters
----------
data : DataFrame
Pandas DataFrame that contains anime show data
top_n : Integer
Determines how many studios that will be placed onto the graph
Notes
-----
Visualization Type: Line Plot
File Path: plots/rq3_studios_yearly.png
If the top_n value goes over the length of "distinct_colors", the palette
will be shifted back to the default, which has indistinct colors
Top_n is determined by the overall amount of anime made with the studio
"""
yearly = data[["studio", "aired_from_year"]]
# The line below prevents 2018 b/c the data was scraped during that year,
# therefore incomplete
yearly = data[data["aired_from_year"] < 2018]
yearly = pd.concat([yearly["aired_from_year"],
pd.get_dummies(yearly["studio"]
.str.split(", ", expand=True),
prefix="", prefix_sep="")], axis=1)
yearly = yearly.groupby("aired_from_year").sum() \
.groupby(level=0, axis=1).sum().reset_index()
top_studios = data["studio"].str.split(", ", expand=True).stack() \
.str.get_dummies().sum().sort_values(ascending=False) \
.iloc[:top_n]
yearly = \
yearly.loc[:, yearly.columns.isin(list(top_studios.index)
+ ["aired_from_year"])]
palette = distinct_colors[:top_n] if top_n < len(distinct_colors) else None
fig, ax = plt.subplots()
fig.set_size_inches(15, 8)
sns.lineplot(x="aired_from_year", y="value", hue="Studio",
data=pd.melt(yearly, ["aired_from_year"])
.rename(columns={"variable": "Studio"}),
palette=palette, ax=ax)
fig.suptitle(f"Top {top_n} Studios by Year (Anime Counts)")
ax.set_xlabel("Year")
ax.set_ylabel("Amount of Anime")
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
fig.savefig("plots/rq3_studios_yearly.png", bbox_inches="tight")
def main(anime_data):
"""
Runs all the data analysis and visualization for research question three
Parameters
----------
anime_data : DataFrame
Pandas DataFrame that contains anime show data before 2018
"""
plot_yearly_studio_score(anime_data)
plot_yearly_studio_score(anime_data, 50)
plot_studio_averages(anime_data)
plot_genre_average(anime_data)
plot_genre_average(anime_data, genres=["Comedy", "Romance", "Action"])
plot_studio_amounts(anime_data)
plot_studio_count_yearly(anime_data)