-
Notifications
You must be signed in to change notification settings - Fork 0
/
createHistogram.py
192 lines (163 loc) · 6.56 KB
/
createHistogram.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
import sys
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import time
import re
import os
from datetime import date, datetime, timedelta
from collections import OrderedDict
from matplotlib.ticker import ScalarFormatter
def createHistogram(df, querystring='', time_column='timespan', time_format='months', include_normalised=False):
df = df.sort_values(by=[time_column])
endstring = 10
if time_format == 'months':
endstring = 7
elif time_format == 'days':
endstring = 10
li_dates = [date[0:endstring] for date in df[time_column]]
li_timeticks = []
dateformat = '%d-%m-%y'
df_histo = pd.DataFrame()
if time_format == 'months':
df['date_histo'] = li_dates
df = df.groupby(by=['date_histo']).agg(['count'])
elif time_format == 'days':
df['date_histo'] = li_dates
df = df.groupby(by=['date_histo']).agg(['count'])
# Create new list of all dates between start and end date
# Sometimes one date has zero counts, and gets skipped by matplotlib
li_dates = []
li_check_dates = []
if time_format == 'months':
d1 = datetime.strptime(df.index[0], "%Y-%m").date() # start date
d2 = datetime.strptime(df.index[len(df) - 1], "%Y-%m").date() # end date
delta = d2 - d1 # timedelta
for i in range(delta.days + 1):
date = d1 + timedelta(days=i)
date = str(date)[:endstring]
if date not in li_dates:
li_dates.append(date)
li_check_dates.append(date)
if time_format == 'days':
d1 = datetime.strptime(df.index[0], "%Y-%m-%d").date() # start date
d2 = datetime.strptime(df.index[len(df) - 1], "%Y-%m-%d").date()# end date
# print(d1, d2)
delta = d2 - d1 # timedelta
for i in range(delta.days + 1):
date_object = d1 + timedelta(days=i)
str_date = date_object.strftime('%Y-%m-%d')
li_dates.append(date_object)
li_check_dates.append(str_date)
# Create list of counts. 0 if it does not appears in previous DataFrame
li_counts = [0 for i in range(len(li_dates))]
li_index_dates = df.index.values.tolist()
for index, indate in enumerate(li_check_dates):
# print(indate)
if indate in li_index_dates and df.loc[indate][1] > 0:
li_counts[index] = df.loc[indate][1]
else:
li_counts[index] = 0
print(li_index_dates)
df_histo['date'] = li_dates
df_histo['count'] = li_counts
#create list of average counts
if include_normalised:
li_av_count = []
for i in range(len(df_histo)):
av_count = (df_histo['id'][i] / di_totalcomment[df_histo['date'][i]]) * 100
li_av_count.append(av_count)
df_histo['av_count'] = li_av_count
if not os.path.exists('output/'):
os.makedirs('output/')
print(df_histo.head())
print('Writing raw data to "' + 'output/histogram_data_' + querystring + '.csv')
# Safe the metadata
df_histo.to_csv('output/histogram_data_' + querystring + '.csv', index=False)
print('Making histogram...')
# Plot the graph!
fig, ax = plt.subplots(1,1)
fig = plt.figure(figsize=(12, 8))
fig.set_dpi(100)
ax = fig.add_subplot(111)
#ax2 = ax.twinx()
if time_format == 'days':
ax.xaxis.set_major_locator(matplotlib.dates.DayLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter(dateformat))
elif time_format == 'months':
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter(dateformat))
ax.get_yaxis().set_major_formatter(plt.FuncFormatter(lambda x, loc: "{:,}".format(int(x))))
df_histo.plot(ax=ax, y='count', kind='bar', legend=False, width=.9, color='#52b6dd');
#df_histo.plot(ax=ax2, y='av_count', legend=False, kind='line', linewidth=2, color='#d12d04');
ax.set_axisbelow(True)
# ax.set_xticks(xticks)
ax.set_xticklabels(df_histo['date'], rotation='vertical')
ax.grid(color='#e5e5e5',linestyle='dashed', linewidth=.6)
ax.set_ylabel('Absolute amount', color='#52b6dd')
#ax2.set_ylabel('Percentage of total comments', color='#d12d04')
#ax2.set_ylim(bottom=0)
# Reduce tick labels when there's more a lot of day dates:
if time_format == 'days' and len(set(li_dates)) > 50:
for index, label in enumerate(ax.xaxis.get_ticklabels()):
#print(label)
if label.get_text().endswith('-01'):
label.set_visible(True)
else:
label.set_visible(False)
plt.title('Posts containing "' + querystring + '"')
print('Saving svg file as "output/histogram_' + querystring + '.svg"')
plt.savefig('output/histogram_' + querystring + '.svg', dpi='figure',bbox_inches='tight')
print('Saving png file as "output/histogram_' + querystring + '.png"')
plt.savefig('output/histogram_' + querystring + '.png', dpi='figure',bbox_inches='tight')
print('Done! Saved .csv of data and .png & .svg in folder \'output/\'')
# show manual if needed
if len(sys.argv) < 2:
print()
print("Creates a histogram of occurances of substring per day or month.")
print("Saves the data in a csv file and visualises in .png and .svg.")
print()
print("Usage: python3 createHistogram.py [--source] [--output] [--timespan] [--timecolumn]")
print()
print("--source: the relative path to a csv file from 4CAT (e.g. 'data/datasheet.csv').")
print("--string: the string that was filtered on in the csv. Used as plot title and output file.")
print("--timespan (optional): default 'days' - the separation of the histogram bars. Can be 'days' or 'months'.")
print("--timecol (optional): default 'timespan' - the csv column in which the time values are stored. Should start with format dd-mm-yyyy.")
print()
print("Example: python createHistogram.py --input=data/4cat-datasheet.csv --string=obama --timespan=months --timecolumn=months")
print()
sys.exit(1)
else:
li_args = []
source = ''
output = ''
querystring = ''
time_column = 'timestamp'
timespan = 'days'
# Interpret command line arguments
for arg in sys.argv:
if arg[0:9] == "--source=":
source = arg[9:len(arg)]
li_args.append(source)
elif arg[0:9] == "--string=":
querystring = arg[9:len(arg)]
li_args.append(querystring)
elif arg[0:11] == "--timespan=":
timespan = arg[11:len(arg)]
li_args.append(timespan)
elif arg[0:13] == "--timecolumn=":
time_column = arg[13:len(arg)]
li_args.append(time_column)
if source == '' or not os.path.isfile(source):
print("Please provide a valid input file like this: --source=data/datasheet.csv")
sys.exit(1)
elif querystring == '':
print("Please provide what word(s) your input file is filtered on.")
print("This is used as plot title and output name.")
print("For instance, if you use a csv with mentions of 'obama',")
print("type --string=obama")
sys.exit(1)
else:
df = pd.read_csv(source)
createHistogram(df, querystring=querystring, time_format=timespan, time_column=time_column)