/
plotting.py
210 lines (177 loc) · 6.36 KB
/
plotting.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
import os
import uuid
from types import MethodType
import numpy as np
import pandas as pd
from bokeh.resources import CDN
from bokeh.plotting import figure, ColumnDataSource
from bokeh.embed import autoload_static
from bokeh.models import HoverTool
COLORS = ["#1f77b4", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728",
"#ff9896", "#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2",
"#f7b6d2", "#7f7f7f", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5"]
TOOLS = ['pan', 'wheel_zoom', 'box_zoom', 'resize', 'reset', 'previewsave', 'box_select', 'hover']
def plot_df(df,
tools=TOOLS,
title='',
x_axis_type='datetime',
line_width=2,
background_fill= '#eeeff0',
alpha=0.7,
style='o-',
plot_width=600,
plot_height=400,
xlabel='',
ylabel=''):
"""Creates a bokeh plot of dataframe, one line per column"""
plot = figure(x_axis_type=x_axis_type,
tools=','.join(tools),
title=title,
background_fill=background_fill,
plot_width=plot_width,
plot_height=plot_height)
plot.xaxis.axis_label = xlabel
plot.yaxis.axis_label = ylabel
info = df.index
if isinstance(df.index, pd.tseries.index.DatetimeIndex):
info = [d.strftime('%d/%m/%Y %H:%M:%S') for d in info]
for idx, ts in enumerate(df):
source = ColumnDataSource(
data=dict(x=df.index,
y=df[ts].values,
info=info,
)
)
color = COLORS[idx%len(COLORS)]
plot.line(df.index, df[ts].values,
line_color=color,
line_width=line_width,
alpha=alpha,
legend=ts,
source=source)
if style == 'o-':
plot.circle(df.index, df[ts].values, color=color, fill_color=None, size=10, legend=ts, source=source)
if 'hover' in tools:
hover = plot.select(dict(type=HoverTool))
hover.tooltips = [(xlabel, "@info"),
(ylabel, "$y"),
]
return plot
def setcol(x):
"""Sets color for a given value"""
if np.isnan(x):
return '#e2e2e2'
elif x<0:
return '#cc7878'
else:
return '#a5bab7'
def heatmap_df(df,
tools=TOOLS,
title='',
alpha=0.7,
plot_width=900,
plot_height=400,
xlabel='',
ylabel='',
x_axis_location='above'):
"""Creates a bokeh plot of dataframe as a heatmap"""
# pre-condition as columns and index need to be list of string
x = list(map(str, df.index))
y = list(df.columns)
# set color for every cell
ys = []
xs = []
for xi in x:
for yi in y:
ys.append(yi)
xs.append(xi)
value = df.values.ravel()
color = [setcol(v) for v in value]
source = ColumnDataSource(
data=dict(x=xs,
y=ys,
color=color,
value=value,
)
)
plot = figure(title=title,
tools=tools,
x_range=x,
y_range=list(reversed(y)),
plot_width=plot_width,
plot_height=plot_height,
x_axis_location=x_axis_location)
plot.rect('x', 'y', 0.95, 0.95, source=source, color='color', line_color=None)
plot.grid.grid_line_color = None
plot.axis.axis_line_color = None
plot.axis.major_tick_line_color = None
plot.axis.major_label_standoff = 0
plot.xaxis.axis_label = xlabel
plot.yaxis.axis_label = ylabel
if 'hover' in tools:
hover = plot.select(dict(type=HoverTool))
hover.tooltips = [(xlabel, "$x"),
(ylabel, "$y"),
('value', '@value'),
]
return plot
def iplot(self,
plottype='linear',
jspath=None,
title='',
browser='chrome',
tools=TOOLS,
x_axis_type='datetime',
line_width=2,
background_fill= '#eeeff0',
alpha=0.7,
plot_width=900,
plot_height=400,
xlabel='',
ylabel='',
style='o-'):
"""Writes javascript in given location, embeds it in a html saved in same location, and opens it in a browser
Example
-------
>>> import pandas as pd
>>> import pandasaddons
>>> rdf = pd.RandomDataFrame(index_type='datetime')
>>> rdf.iplot()
>>> rdf = pd.RandomDataFrame(index_type='linear')-0.5
>>> rdf.iplot(plottype='heatmap', xlabel='x', ylabel='y')
"""
if plottype.lower() == 'heatmap':
plot = heatmap_df(self,
tools=tools,
title=title,
alpha=alpha,
plot_width=plot_width,
plot_height=plot_height,
xlabel=xlabel,
ylabel=ylabel,
x_axis_location='above')
else:
plot = plot_df(self,
tools=tools,
title=title,
x_axis_type=x_axis_type,
line_width=line_width,
background_fill=background_fill,
alpha=alpha,
style=style,
plot_width=plot_width,
plot_height=plot_height,
xlabel=xlabel,
ylabel=ylabel)
filename = str(uuid.uuid4())
this_jspath = jspath if jspath else os.environ['TMP']
jsfilename = os.path.join(this_jspath, filename+'.js')
htmlfilename = os.path.join(this_jspath, filename+'.html' )
js, tag = autoload_static(plot, CDN, script_path=jsfilename)
with open(jsfilename, 'w') as f:
f.write(js)
html = '<html><div>'+tag+'</div></html>'
with open(htmlfilename, 'w') as f:
f.write(html)
os.system('start {browser}.exe "{htmlfilename}"'.format(**locals()))
pd.DataFrame.iplot = MethodType(iplot, None, pd.DataFrame)