-
Notifications
You must be signed in to change notification settings - Fork 0
/
analytics.py
183 lines (140 loc) · 6.31 KB
/
analytics.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
from bokeh.plotting import figure, output_file, show
from bokeh.models import DatetimeTicker, FactorRange
from database import Database
from defineTimezone import *
import logging
import matplotlib.pyplot as plt
import matplotlib.axes
import numpy as np
import pandas as pd
logging.basicConfig(level = logging.DEBUG)
class Analytics:
def __init__(self, databaseName = 'VirtualSenseHat.db'): # "fakeData.db"
self.databaseName = databaseName
self.database = Database(self.databaseName)
self.currentDate = datetime(2019, 4, 5).date() #set 05/04/2019 as our default current date
def prepareDataLinePlot(self, dataDate = None):
# prepare some data
if dataDate == None:
dataDate = self.currentDate
self.time, self.temperature, self.humidity = self.database.getWeatherDataOn(dataDate)
logging.debug('Time series: ')
logging.debug(self.time)
logging.debug('Temperature series: ')
logging.debug(self.temperature)
logging.debug('Humidity series: ')
logging.debug(self.humidity)
self.dataDate = dataDate
def prepareDataBarPlot(self):
self.date, self.avgTemperature, self.avgHumidity = self.database.getAverageWeatherData(endDate = self.currentDate)
logging.debug('Date series: ')
logging.debug(self.date)
logging.debug('Avg temperature series: ')
logging.debug(self.avgTemperature)
logging.debug('Avg humidity series: ')
logging.debug(self.avgHumidity)
def plotLineGraph(self, x_list, y_list, value, unit):
figureTitle = "{} for {}".format(value, self.dataDate.strftime(DATE_FORMAT))
logging.debug("Plotting {}".format(figureTitle))
# output to static HTML file
output_file("{}Plot.html".format(value))
x_axis_label= 'Time'
y_axis_label= '{} ({})'.format(value, unit)
# create a new plot with a title and axis labels
p = figure(plot_width=1200, plot_height=600, title=figureTitle, x_axis_label=x_axis_label, y_axis_label=y_axis_label, x_axis_type="datetime")
# add a line renderer with legend and line thickness
p.xaxis.ticker = DatetimeTicker(desired_num_ticks = 24)
p.line(x_list, y_list, legend=value, line_width=2)
p.y_range.start = 0
if unit == "*C":
p.y_range.end = 70
else:
p.y_range.end = 50
# show the results
show(p)
def plotBarGraph(self, x_list, y_list, value, unit):
figureTitle = "{} for {} to {}".format(value, x_list[0], x_list[-1])
logging.debug("Plotting {}".format(figureTitle))
output_file = "{}Plot.html".format(value.title().replace(' ', ''))
x_axis_label='Date'
y_axis_label='{} ({})'.format(value, unit)
p = figure(x_range=self.date, plot_width=600, plot_height=400, title= figureTitle, x_axis_label=x_axis_label, y_axis_label=y_axis_label, toolbar_location=None, tools="")
#x_range=self.date, x_range=FactorRange(self.date)
#p.xaxis.ticker = days
p.vbar(x=x_list, top=y_list, width=0.9)
p.ygrid.grid_line_color = "grey"
p.y_range.start = 0
if unit == "*C":
p.y_range.end = 70
else:
p.y_range.end = 50
show(p)
def plotTemperature(self):
self.plotLineGraph(self.time, self.temperature, "Temperature", "*C")
def plotHumidity(self):
self.plotLineGraph(self.time, self.humidity, "Humidity", "%")
def plotAvgTemperature(self):
self.plotBarGraph(self.date, self.avgTemperature, "Average temperature", "*C")
def plotAvgHumidity(self):
self.plotBarGraph(self.date, self.avgHumidity, "Average humidity", "%")
def plotLineMatplotlib(self, x_list, y_list, value, unit):
figureTitle = "{} for {}".format(value, self.dataDate.strftime(DATE_FORMAT))
logging.debug("Plotting {}".format(figureTitle))
output_file = "{}Plot.png".format(value.title().replace(' ', ''))
df=pd.DataFrame({'time': x_list, value : y_list})
# plot
figure, axes = plt.subplots(figsize=(16,6))
axes.plot('time', value, data=df, marker='o', color='mediumvioletred')
plt.title(figureTitle)
plt.xlabel("Time")
plt.ylabel('{} ({})'.format(value, unit))
plt.legend()
plt.grid(True)
plt.xticks([i.strftime("%H:%M") for i in x_list])
logging.debug(plt.xticks())
if unit == "*C":
plt.ylim(0,70)
else:
plt.ylim(0,50)
plt.savefig(output_file)
plt.show()
def plotBarMatplotlib(self, x_list, y_list, value, unit):
figureTitle = "{} for {} to {}".format(value, x_list[0], x_list[-1])
logging.debug("Plotting {}".format(figureTitle))
output_file = "{}Plot.png".format(value.title().replace(' ', ''))
df=pd.DataFrame({'date': x_list, value : y_list})
# plot
figure, axes = plt.subplots(figsize=(16,6))
axes.bar('date', value, data=df, color='mediumvioletred')
plt.title(figureTitle)
plt.xlabel('Date')
plt.ylabel('{} ({})'.format(value, unit))
plt.legend()
plt.grid(axis = 'y')
plt.xticks(self.date)
logging.debug(plt.xticks())
if unit == "*C":
plt.ylim(0,70)
else:
plt.ylim(0,50)
plt.savefig(output_file)
plt.show()
def plotTemperatureMatplotlib(self):
self.plotLineMatplotlib(self.time, self.temperature, "Temperature", "*C")
def plotHumidityMatplotlib(self):
self.plotLineMatplotlib(self.time, self.humidity, "Humidity", "%")
def plotAvgTemperatureMatplotlib(self):
self.plotBarMatplotlib(self.date, self.avgTemperature, "Average temperature", "*C")
def plotAvgHumidityMatplotlib(self):
self.plotBarMatplotlib(self.date, self.avgHumidity, "Average humidity", "%")
analytics = Analytics()
analytics.prepareDataLinePlot()
analytics.plotTemperature() #Using Bokeh
analytics.plotHumidity() #Using Bokeh
analytics.plotTemperatureMatplotlib()
analytics.plotHumidityMatplotlib()
analytics.prepareDataBarPlot()
analytics.plotAvgHumidity() #Using Bokeh
analytics.plotAvgTemperatureMatplotlib()
analytics.plotAvgHumidityMatplotlib()
analytics.plotAvgTemperature() #Using Bokeh