-
Notifications
You must be signed in to change notification settings - Fork 0
/
plotting_utils.py
executable file
·331 lines (267 loc) · 10.4 KB
/
plotting_utils.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plotting: Central repository for plots
Uses:
1) Templates for plot types
2) Personalized style
References:
1) Matplotlib
a) https://matplotlib.org/tutorials/introductory/customizing.html
b) https://matplotlib.org/gallery/style_sheets/style_sheets_reference.html
2) Pandas
a)https://pandas.pydata.org/pandas-docs/version/0.23.4/visualization.html
3) Seaborn
a) https://seaborn.pydata.org/tutorial.html
b) https://seaborn.pydata.org/examples/index.html
4) Colormaps:
a) https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html
b) https://seaborn.pydata.org/tutorial/color_palettes.html
Created on Mon Jan 27 12:39:06 2020
@author: abishekk
"""
import matplotlib as mpl
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
class Plotting(object):
"""
Class for personalized plotting functions. Use as a template to change
default values, font and color palette preferences across a project
"""
##########################################################################
def __init__(self):
"""
Set matplotlib style preferences
Returns
-------
None.
"""
font_size = 14
label_size = 18
tick_size = 12
plt.style.use('seaborn')
mpl.rc('lines',linewidth=3.0)
mpl.rc('axes', titlesize=label_size, labelsize=label_size,
linewidth=0.8,edgecolor='0.25')
# remove box
#mpl.rc('axes.spines',top=False,right=False)
mpl.rc('xtick',labelsize=tick_size)
mpl.rc('ytick',labelsize=tick_size)
mpl.rc('xtick.major',size=3.0)
mpl.rc('ytick.major',size=3.0)
# Font: cm font for all text, change mathtext to cm
# Note:
# Use mpl.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
# to find fonts on the system
# If CMU fonts are missing:
# $brew tap homebrew/cask-fonts
# $brew cask install font-computer-modern
font_style = {'family' : 'sans-serif',
'sans-serif' : ['CMU Sans Serif'],
'size': font_size}
mpl.rc('font', **font_style)
# Install latex packages: type1cm, dvipng
# Issues: special char such as _ are not read correctly until '\' is
# provided.
#mpl.rc('text',usetex=True)
mpl.rc('mathtext', fontset='cm')
##########################################################################
def plot_colored_sinusoidal_lines(self):
"""
Plot sinusoidal lines with colors following the style color cycle.
Use: visualize formatting
"""
# crearte sine curves
L = 2 * np.pi
x = np.linspace(0, L)
nb_colors = len(plt.rcParams['axes.prop_cycle'])
shift = np.linspace(0, L, nb_colors, endpoint=False)
for s in shift:
plt.plot(x, np.sin(x + s), '-')
plt.xlim([x[0], x[-1]])
plt.xlabel('$x$')
plt.ylabel('$\sin(x)$')
plt.title('Shifted sine plots')
plt.show()
##########################################################################
##########################################################################
### I - DATA EXPLORATION ###
##########################################################################
##########################################################################
def pandas_histogram(self, dataframe, fig_size=(20,20)):
"""
histogram from pandas dataframe or series
Parameters
----------
dataframe : Pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.
"""
dataframe.hist(bins=50,figsize=fig_size)
plt.show()
##########################################################################
def pandas_scatter_plot(self,dataframe,x_series,y_series, size,
size_label,color):
"""
Parameters
----------
dataframe : pandas dataframe
x_series : str, series for x
y_series : str, series for y
size : series, determines size of scatter dot
size_label: str, defines legend string
color : str, determines color of scatter dot from series
Returns
-------
None.
eg.
myplot.pandas_scatter_plot(housing_data,'latitude','longitude',
housing_data['population']/100., 'population', 'median_house_value')
"""
# Jet is not a great colormap
# Try viridis, inferno, magma, tab20c
dataframe.plot(kind="scatter", x=x_series, y=y_series, alpha=0.4,
s=size, label=size_label,
c=color, cmap=plt.get_cmap("viridis"), colorbar=True)
plt.show()
##########################################################################
def pandas_scatter_matrix(self, dataframe, fig_size=(12,12)):
"""
Tool for data exploration, observing correlations
Parameters
----------
dataframe : pandas dataframe
fig_size: tuple, width x height
Returns
-------
None.
eg.
attributes = ["median_house_value","median_income","total_rooms"]
myplot.pandas_scatter_matrix(housing_data[attributes])
"""
pd.plotting.scatter_matrix(dataframe,figsize=fig_size,diagonal='kde')
plt.show()
##########################################################################
def sns_scatter_matrix(self,dataframe,hue_str=None,diag_plt='kde'):
"""
Pair-wise scatter plot between variables in data. Plots on diagonal
can be histogram or kde.
Parameters
----------
dataframe : pandas dataframe
hue_str : str, optional
Column name in dataframe to use for color. Default is None
diag_plt : str, optional
Type of plot on diagonal('hist','kde'). The default is 'kde'.
Returns
-------
None.
eg.
iris = sns.load_dataset('iris')
myplot.sns_scatter_matrix(iris,'species')
"""
# Using pairplot
# Note: PairGrid is much more flexible than pairplot but also
# considerably slower
sns.pairplot(dataframe, hue=hue_str, palette='viridis',
kind='scatter', diag_kind=diag_plt, height=2.5)
plt.show()
##########################################################################
def sns_lineplot(self,dataframe, x_name=None, y_name=None, hue_str=None):
"""
Line plot
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
df = pd.DataFrame(dict(time=np.arange(500),
value=np.random.randn(500).cumsum()))
myplot.sns_lineplot(df,'time','value')
"""
sns.lineplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
##########################################################################
def sns_boxenplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"""
Boxenplot - similar to box plots but provides more information about
the distribution as it plots more quantiles. Useful for large datasets
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
diamonds = sns.load_dataset('diamonds').sort_values('color')
myplot.sns_boxenplot(diamonds,'color','price')
"""
sns.boxenplot(data=dataframe, x=x_name, y=y_name, hue=hue_str,
palette='deep')
plt.show()
##########################################################################
def sns_barplot(self, dataframe, x_name=None, y_name=None, hue_str=None):
"""
Barplot - categorical estimatation
Parameters
----------
dataframe : dataframe
data container
x_name : str, optional
column name for the x-axis. The default is None.
y_name : str, optional
column name for the y-axis. The default is None.
hue_str : str, optional
name of categorical data to color by. The default is None.
Returns
-------
None.
eg.
titanic = sns.load_dataset('titanic')
myplot.sns_barplot(titanic,'sex','survived','class')
"""
sns.barplot(data=dataframe, x=x_name, y=y_name, hue=hue_str)
plt.show()
##########################################################################
def sns_heatmap(self, data2d, data_type):
"""
Heatmap of 2d data with data annotated
Parameters
----------
data2d : data in 2d representation
data_type : type of data to be annotated - 'int', 'float'
fig_size: tuple, define figure size
Returns
-------
None.
eg.
flights=sns.load_dataset('flights').pivot('month','year','passengers')
myplt.sns_heatmap(flights,'int')
"""
data_string = {'int':'d','float':'0.1f'}
sns.heatmap(data2d, annot=True, linewidths=0.5,
fmt=data_string[data_type])
plt.show()
##########################################################################
### II - MODEL VISUALIZATION ###
##########################################################################