/
__init__.py
343 lines (287 loc) · 13.2 KB
/
__init__.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
332
333
334
335
336
337
338
339
340
341
342
343
import os
import warnings
from io import BytesIO
from tempfile import NamedTemporaryFile
# Python3 compatibility
try: basestring = basestring
except: basestring = str
from matplotlib import animation
from matplotlib import ticker
from matplotlib import rc_params_from_file
from param.parameterized import bothmethod
from ..core.options import Cycle, Palette, Options, StoreOptions
from ..core import Dimension, Layout, NdLayout, Overlay
from ..core.io import Exporter
from .annotation import * # pyflakes:ignore (API import)
from .chart import * # pyflakes:ignore (API import)
from .chart3d import * # pyflakes:ignore (API import)
from .path import * # pyflakes:ignore (API import)
from .plot import * # pyflakes:ignore (API import)
from .raster import * # pyflakes:ignore (API import)
from .tabular import * # pyflakes:ignore (API import)
from . import pandas # pyflakes:ignore (API import)
from . import seaborn # pyflakes:ignore (API import)
# Tags used when matplotlib output is to be embedded in HTML
IMAGE_TAG = "<center><img src='{src}' style='max-width:100%'/><center/>"
VIDEO_TAG = """
<center><video controls style='max-width:100%'>
<source src='{src}' type='{mime_type}'>
Your browser does not support the video tag.
</video><center/>"""
HTML_TAGS = {
'base64': 'data:{mime_type};base64,{b64}', # Use to embed data
'svg': IMAGE_TAG,
'png': IMAGE_TAG,
'gif': IMAGE_TAG,
'webm': VIDEO_TAG,
'mp4': VIDEO_TAG
}
MIME_TYPES = {
'svg': 'image/svg+xml',
'png': 'image/png',
'gif': 'image/gif',
'webm': 'video/webm',
'mp4': 'video/mp4'
}
# <format name> : (animation writer, format, anim_kwargs, extra_args)
ANIMATION_OPTS = {
'webm': ('ffmpeg', 'webm', {},
['-vcodec', 'libvpx', '-b', '1000k']),
'mp4': ('ffmpeg', 'mp4', {'codec': 'libx264'},
['-pix_fmt', 'yuv420p']),
'gif': ('imagemagick', 'gif', {'fps': 10}, []),
'scrubber': ('html', None, {'fps': 5}, None)
}
def opts(el, size):
"Returns the plot options with supplied size (if not overridden)"
obj = el.last if isinstance(el, HoloMap) else el
return dict(figure_inches=size, **Store.lookup_options(obj, 'plot').options)
def get_plot_size(obj, percent_size):
"""
Given a holoviews object and a percentage size, apply heuristics
to compute a suitable figure size. For instance, scaling layouts
and grids linearly can result in unwieldy figure sizes when there
are a large number of elements. As ad hoc heuristics are used,
this functionality is kept separate from the plotting classes
themselves.
Used by the IPython Notebook display hooks and the save
utility. Note that this can be overridden explicitly per object
using the figure_size and size plot options.
"""
def rescale_figure(percent_size):
factor = percent_size / 100.0
return (Plot.figure_inches[0] * factor,
Plot.figure_inches[1] * factor)
if isinstance(obj, (Layout, NdLayout)) and not isinstance(obj, Overlay):
return (obj.shape[1]*rescale_figure(percent_size)[1],
obj.shape[0]*rescale_figure(percent_size)[0])
elif isinstance(obj, GridSpace):
max_dim = max(obj.shape)
# Reduce plot size as GridSpace gets larger
shape_factor = 1. / max_dim
# Expand small grids to a sensible viewing size
expand_factor = 1 + (max_dim - 1) * 0.1
scale_factor = expand_factor * shape_factor
return (scale_factor * obj.shape[0] * rescale_figure(percent_size)[0],
scale_factor * obj.shape[1] * rescale_figure(percent_size)[1])
else:
return rescale_figure(percent_size)
class MPLPlotRenderer(Exporter):
"""
Exporter used to render data from matplotlib, either to a stream
or directly to file.
The __call__ method renders an HoloViews component to raw data of
a specified matplotlib format. The save method is the
corresponding method for saving a HoloViews objects to disk.
The save_fig and save_anim methods are used to save matplotlib
figure and animation objects. These match the two primary return
types of plotting class implemented with matplotlib.
"""
fig = param.ObjectSelector(default='svg',
objects=['png', 'svg', None], doc="""
Output render format for static figures. If None, no figure
rendering will occur. """)
holomap = param.ObjectSelector(default='gif',
objects=['webm','mp4', 'gif', None], doc="""
Output render multi-frame (typically animated) format. If
None, no multi-frame rendering will occur.""")
size=param.Integer(100, doc="""
The rendered size as a percentage size""")
fps=param.Integer(20, doc="""
Rendered fps (frames per second) for animated formats.""")
dpi=param.Integer(None, allow_None=True, doc="""
The render resolution in dpi (dots per inch)""")
info_fn = param.Callable(None, allow_None=True, constant=True, doc="""
MPLPlotRenderer does not support the saving of object info metadata""")
key_fn = param.Callable(None, allow_None=True, constant=True, doc="""
MPLPlotRenderer does not support the saving of object key metadata""")
# Error messages generated when testing potentially supported formats
HOLOMAP_FORMAT_ERROR_MESSAGES = {}
def __call__(self, obj, fmt=None):
"""
Render the supplied HoloViews component using matplotlib.
"""
if isinstance(obj, AdjointLayout):
obj = Layout.from_values(obj)
element_type = obj.type if isinstance(obj, HoloMap) else type(obj)
try:
plotclass = Store.registry[element_type]
except KeyError:
raise Exception("No corresponding plot type found for %r" % type(obj))
plot = plotclass(obj, **opts(obj, get_plot_size(obj, self.size)))
if fmt is None:
fmt = self.holomap if len(plot) > 1 else self.fig
if fmt is None: return
if len(plot) > 1:
(writer, _, anim_kwargs, extra_args) = ANIMATION_OPTS[fmt]
anim = plot.anim(fps=self.fps)
if extra_args != []:
anim_kwargs = dict(anim_kwargs, extra_args=extra_args)
data = self.anim_data(anim, fmt, writer, **anim_kwargs)
else:
data = self.figure_data(plot(), fmt, **({'dpi':self.dpi} if self.dpi else {}))
return data, {'file-ext':fmt,
'mime_type':MIME_TYPES[fmt]}
@bothmethod
def supported_holomap_formats(self_or_cls, optional_formats):
"Optional formats that are actually supported by this renderer"
supported = []
with param.logging_level('CRITICAL'):
self_or_cls.HOLOMAP_FORMAT_ERROR_MESSAGES = {}
for fmt in optional_formats:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
fig = plt.figure()
anim = animation.FuncAnimation(fig, lambda x: x, frames=[0,1])
(writer, fmt, anim_kwargs, extra_args) = ANIMATION_OPTS[fmt]
if extra_args != []:
anim_kwargs = dict(anim_kwargs, extra_args=extra_args)
renderer = self_or_cls.instance(dpi=72)
renderer.anim_data(anim, fmt, writer, **anim_kwargs)
plt.close(fig)
supported.append(fmt)
except Exception as e:
self_or_cls.HOLOMAP_FORMAT_ERROR_MESSAGES[fmt] = str(e)
return supported
@bothmethod
def save(self_or_cls, obj, basename, fmt=None, key={}, info={}, options=None, **kwargs):
"""
Save a HoloViews object to file, either using an explicitly
supplied format or to the appropriate default.
"""
if info or key:
raise Exception('MPLPlotRenderer does not support saving metadata to file.')
with StoreOptions.options(obj, options, **kwargs):
rendered = self_or_cls(obj, fmt)
if rendered is None: return
(data, info) = rendered
filename ='%s.%s' % (basename, info['file-ext'])
with open(filename, 'wb') as f:
f.write(self_or_cls.encode(rendered))
def anim_data(self, anim, fmt, writer, **anim_kwargs):
"""
Render a matplotlib animation object and return the corresponding data.
"""
anim_kwargs = dict(anim_kwargs, **({'dpi':self.dpi} if self.dpi is not None else {}))
anim_kwargs = dict(anim_kwargs, **({'fps':self.fps} if fmt =='gif' else {}))
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.%s' % fmt) as f:
anim.save(f.name, writer=writer,
**dict(anim_kwargs, **({'dpi':self.dpi} if self.dpi else {})))
video = open(f.name, "rb").read()
return video
def figure_data(self, fig, fmt='png', bbox_inches='tight', **kwargs):
"""
Render matplotlib figure object and return the corresponding data.
Similar to IPython.core.pylabtools.print_figure but without
any IPython dependency.
"""
kw = dict(
format=fmt,
facecolor=fig.get_facecolor(),
edgecolor=fig.get_edgecolor(),
dpi=self.dpi,
bbox_inches=bbox_inches,
)
kw.update(kwargs)
bytes_io = BytesIO()
fig.canvas.print_figure(bytes_io, **kw)
data = bytes_io.getvalue()
if fmt == 'svg':
data = data.decode('utf-8')
return data
Store.renderer = MPLPlotRenderer
def set_style(key):
"""
Select a style by name, e.g. set_style('default'). To revert to the
previous style use the key 'unset' or False.
"""
if key is None:
return
elif not key or key in ['unset', 'backup']:
if 'backup' in styles:
plt.rcParams.update(styles['backup'])
else:
raise Exception('No style backed up to restore')
elif key not in styles:
raise KeyError('%r not in available styles.')
else:
path = os.path.join(os.path.dirname(__file__), styles[key])
new_style = rc_params_from_file(path)
styles['backup'] = dict(plt.rcParams)
plt.rcParams.update(new_style)
styles = {'default': './default.mplstyle'}
set_style('default')
# Upgrade Dimension formatters to matplotlib
wrapped_formatters = {k: fn if isinstance(fn, ticker.Formatter) else ticker.FuncFormatter(fn)
for k, fn in Dimension.type_formatters.items()}
Dimension.type_formatters.update(wrapped_formatters)
# Define matplotlib based style cycles and Palettes
Cycle.default_cycles.update({'default_colors': plt.rcParams['axes.color_cycle']})
Palette.colormaps.update({cm: plt.get_cmap(cm) for cm in plt.cm.datad})
# Register default Element options
Store.register_plots(style_aliases={'edgecolor': ['ec', 'ecolor'], 'facecolor': ['fc'],
'linewidth': ['lw'], 'edgecolors': ['ec', 'edgecolor'],
'linestyle': ['ls'], 'size': ['s'], 'color': ['c']})
# Charts
Store.options.Curve = Options('style', color=Cycle(), linewidth=2)
Store.options.Scatter = Options('style', color=Cycle(), marker='o')
Store.options.ErrorBars = Options('style', ecolor='k')
Store.options.Bars = Options('style', ec='k', color=Cycle())
Store.options.Histogram = Options('style', ec='k', fc=Cycle())
Store.options.Points = Options('style', color=Cycle(), marker='o')
Store.options.Scatter3D = Options('style', color=Cycle(), marker='o')
# Rasters
Store.options.Image = Options('style', cmap='hot', interpolation='nearest')
Store.options.Raster = Options('style', cmap='hot', interpolation='nearest')
Store.options.HeatMap = Options('style', cmap='RdYlBu_r', interpolation='nearest')
Store.options.HeatMap = Options('plot', show_values=True, xticks=20, yticks=20)
Store.options.RGBA = Options('style', interpolation='nearest')
Store.options.RGB = Options('style', interpolation='nearest')
# Composites
Store.options.Layout = Options('plot', sublabel_format='{Alpha}')
Store.options.GridSpace = Options('style', **{'font.size': 10, 'axes.labelsize': 'small',
'axes.titlesize': 'small'})
# Annotations
Store.options.VLine = Options('style', color=Cycle())
Store.options.HLine = Options('style', color=Cycle())
Store.options.Spline = Options('style', linewidth=2, ec='r')
Store.options.Text = Options('style', fontsize=13)
Store.options.Arrow = Options('style', color='k', linewidth=2, fontsize=13)
# Paths
Store.options.Contours = Options('style', color=Cycle())
Store.options.Path = Options('style', color=Cycle())
Store.options.Box = Options('style', color=Cycle())
Store.options.Bounds = Options('style', color=Cycle())
Store.options.Ellipse = Options('style', color=Cycle())
# Interface
Store.options.TimeSeries = Options('style', color=Cycle())
# Defining the most common style options for HoloViews
GrayNearest = Options(key='style', cmap='gray', interpolation='nearest')
def public(obj):
if not isinstance(obj, type): return False
baseclasses = [Plot, Cycle]
return any([issubclass(obj, bc) for bc in baseclasses])
_public = ["MPLPlotRenderer", "GrayNearest"] + list(set([_k for _k, _v in locals().items() if public(_v)]))
__all__ = _public