-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualisations.py
259 lines (217 loc) · 9.2 KB
/
visualisations.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
#########################################
# Generate report visualization (graphs)
#########################################
import seaborn as sns
import matplotlib.pyplot as plt
import math
import numpy as np
import pandas as pd
import os
# Line plot of new, existing and pre-existing users since specified track opening
def single_track_opening(data_selected, name_selected):
data_selected=data_selected[1:].reset_index(drop=True)
data_selected.plot(title="Activity after "+name_selected+" track opening")
plt.xticks(np.arange(0,len(data_selected), 1.0))
plt.ylim(bottom=0)
plt.xlabel("Weeks from track opening")
plt.ylabel("Activity")
plt.tight_layout()
# plt.show(block=False)
figure_name = "Activity comparison to same track opening last year"
# print("Graph generated - %s" %figure_name)
if not os.path.isdir("Output_files"):
os.mkdir("Output_files")
os.chdir("Output_files")
file_formate = 'png'
plt.savefig(figure_name, bbox_inches='tight', format=file_formate)
fig_dir=os.getcwd()
os.chdir("..")
plt.close()
return figure_name+"."+file_formate, fig_dir
# Bar plots comparing a selected track opening and the closes one to it a year before.
# Produces three separate graphs (1) new, (2) existing (3) pre-existing users
def last_year_compare(data_selected, name_selected, data_last_year, name_last_year):
col_last_year = data_last_year.columns
cols_selected = data_selected.columns
# Remove first week
data_selected=data_selected[1:]
data_last_year = data_last_year[1:]
# Create new dataframes for each count to plot easily
a=data_last_year[col_last_year[0]].to_frame()
a.columns = [str(name_last_year)]
b=data_selected[cols_selected[0]].to_frame()
b.columns=[str(name_selected)]
df_all=pd.concat([a,b], ignore_index=False, axis=1)
a=data_last_year[col_last_year[1]].to_frame()
a.columns = [str(name_last_year)]
b=data_selected[cols_selected[1]].to_frame()
b.columns=[str(name_selected)]
df_new=pd.concat([a,b], ignore_index=False, axis=1)
a=data_last_year[col_last_year[2]].to_frame()
a.columns = [str(name_last_year)]
b=data_selected[cols_selected[2]].to_frame()
b.columns=[str(name_selected)]
df_existing=pd.concat([a,b], ignore_index=False, axis=1)
# Create figure
graph_no = data_selected.shape[1]
fig, ax = plt.subplots(nrows=graph_no , ncols=1,constrained_layout=True)
figure_name = "Activity comparison to track opening last year"
fig.suptitle(figure_name, fontsize=16)
ax_list = fig.axes
# Uncomment to set all figure to same y axes. 1 of 2
# min_y = 0
# max_y = max([data_selected.max().max(),data_last_year.max().max()])*1.25
for n, one_axis in enumerate(ax_list):
# Uncomment to set all figure to same y axes. 2 of 2
# Set all figure to same y axes
# one_axis.set_ylim(min_y, max_y)
one_axis.axes.set_ylabel("Activity")
one_axis.axes.get_xaxis().set_visible(True)
# Plotting
if n==0:
min_y = 0
max_y = df_all.max().max()*1.25
one_axis.set_ylim(min_y, max_y)
one_axis.set_title("Total (new + existing)")
df_all.plot(kind='bar', ax=one_axis)
# Move legend to left outside of graph and remove box around it
patches, labels = one_axis.get_legend_handles_labels()
plt.setp(one_axis.get_xticklabels(), rotation=0)
one_axis.legend(patches, labels, loc='center left', bbox_to_anchor=(1, 0.5), frameon=False)
if n==1:
min_y = 0
max_y = df_new.max().max()*1.25
one_axis.set_ylim(min_y, max_y)
one_axis.set_title("New from track opening")
df_new.plot(kind='bar', ax=one_axis, legend=False)
plt.setp(one_axis.get_xticklabels(), rotation=0)
if n==2:
min_y = 0
max_y = df_existing.max().max()*1.25
one_axis.set_ylim(min_y, max_y)
one_axis.set_title("Pre-existing participants")
df_existing.plot(kind='bar', ax=one_axis, legend=False)
plt.setp(one_axis.get_xticklabels(), rotation=0)
one_axis.axes.set_xlabel("Weeks from track opening")
# Show value on each bar
for p in one_axis.patches:
one_axis.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
# plt.tight_layout()
# plt.show(block=False)
# print("Graph generated - %s" %figure_name)
if not os.path.isdir("Output_files"):
os.mkdir("Output_files")
os.chdir("Output_files")
file_formate = 'png'
plt.savefig(figure_name, bbox_inches='tight', format=file_formate)
fig_dir = os.getcwd()
os.chdir("..")
plt.close()
return figure_name+"."+file_formate, fig_dir
# Heatmap of active users in each branch.
# Colors normalized to min and max value for each branch in the given daterange
def branch_activity_heatmap(dataframe):
plt.figure()
ax = plt.gca()
labels = dataframe.to_numpy()
dataframe_row = dataframe.div(dataframe.max(axis=1), axis=0)
sns.heatmap(dataframe_row, cmap="coolwarm_r", yticklabels=True, linewidths=.5, robust=True, annot=labels, fmt='',
annot_kws={'size': 8}) # cbar_kws={'orientation': 'horizontal'}
# Set plot properties
ax.set_title('Presence relative to max in each branch')
ax.figure.set_size_inches((12, 10))
ax.tick_params(labelsize=8)
plt.setp(ax.get_xticklabels(), rotation=20, ha="right",
rotation_mode="anchor")
plt.xlabel("")
plt.ylabel('')
plt.tight_layout()
# Colorbar properties
cbar = ax.collections[0].colorbar
cbar.set_ticks([0, .25, .5, .75, 1])
cbar.set_ticklabels(['Min', '25%', '50%', '75%', 'Max'])
# plt.show(block=False)
fig = plt.gcf()
figure_name = "Activity by branch Heatmap"
# print("Graph generated - %s" %figure_name)
if not os.path.isdir("Output_files"):
os.mkdir("Output_files")
os.chdir("Output_files")
file_formate = 'png'
plt.savefig(figure_name, bbox_inches='tight', format=file_formate)
fig_dir = os.getcwd()
os.chdir("..")
plt.close()
return figure_name+"."+file_formate, fig_dir
# Stacked brachart of staff and participants in daterange
def populus_and_staff(dataframe):
plt.figure()
ax = plt.gca()
# Transpose to plot with pandas built in function
dataframe_tf = dataframe.transpose()
column_labels = dataframe_tf.columns
dataframe_tf[[column_labels[0], column_labels[1]]].plot(kind='bar', stacked=True, ax=ax)
# Plot properties
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
plt.xlabel("Weeks")
plt.ylabel('Activity')
plt.tight_layout()
# plt.show(block=False)
fig = plt.gcf()
figure_name = "Activity Stacked Bar Plot (participants, staff)"
# print("Graph generated - %s" %figure_name)
if not os.path.isdir("Output_files"):
os.mkdir("Output_files")
os.chdir("Output_files")
file_formate = 'png'
plt.savefig(figure_name, bbox_inches='tight', format=file_formate)
fig_dir = os.getcwd()
os.chdir("..")
plt.close()
return figure_name+"."+file_formate, fig_dir
# Barchart of activity in daterange by track opening
# Produces seperate figure for each track opening
def activity_by_registration(dataframe):
# plt.figure()
ax = plt.gca()
# Get max and min values from all branches to be used in all graphs
min_y = dataframe.min().min()
max_y = dataframe.max().max()
# Transpose to plot with pandas built in function
dataframe = dataframe.transpose()
series_no = dataframe.shape[1]
dataframe.plot(kind='bar',subplots=True, layout=(series_no, 1), ax=ax, sharex=True, legend=False)
# TODO: THis build in dataframe plot function generates a warning.
# Adjust each plot in figure
fig = plt.gcf()
ax_list = fig.axes
for one_axis in ax_list:
one_axis.set_ylim(min_y, max_y)
# Move legend to left outside of graph and remove box around it
patches, labels = one_axis.get_legend_handles_labels()
one_axis.legend(patches, labels, loc='center left', bbox_to_anchor=(1, 0.5), frameon=False)
# Remove x axis labels from all graphs but bottom one
one_axis.axes.get_xaxis().set_visible(False)
one_axis.set_title("")
if one_axis is ax_list[0]:
one_axis.set_title("Activity each week by registration date (participants+staff)")
if one_axis is ax_list[math.floor(len(ax_list) / 2)]:
one_axis.axes.set_ylabel("Activity")
if one_axis is ax_list[-1]:
one_axis.axes.get_xaxis().set_visible(True)
plt.setp(one_axis.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
plt.tight_layout()
# plt.show(block=False)
fig = plt.gcf()
figure_name = "Activity by registration Bar Plot"
# print("Graph generated - %s" %figure_name)
if not os.path.isdir("Output_files"):
os.mkdir("Output_files")
os.chdir("Output_files")
file_formate='png'
plt.savefig(figure_name, bbox_inches='tight', format=file_formate)
fig_dir = os.getcwd()
os.chdir("..")
plt.close()
return figure_name+"."+file_formate, fig_dir