Debian Codegraph @

mplexporter/utils.py

raw symbols SCIP
1 """
2 Utility Routines for Working with Matplotlib Objects
3 ====================================================
4 """
5 import itertools
6 import io
7 import base64
8
9 import numpy as np
10
11 import warnings
12
13 import matplotlib
14 from matplotlib.colors import colorConverter
15 from matplotlib.path import Path
16 from matplotlib.markers import MarkerStyle
17 from matplotlib.transforms import Affine2D
18 from matplotlib import ticker
19
20
21 def color_to_hex(color):
22 """Convert matplotlib color code to hex color code"""
23 if color is None or colorConverter.to_rgba(color)[3] == 0:
24 return 'none'
25 else:
26 rgb = colorConverter.to_rgb(color)
27 return '#{0:02X}{1:02X}{2:02X}'.format(*(int(255 * c) for c in rgb))
28
29
30 def _many_to_one(input_dict):
31 """Convert a many-to-one mapping to a one-to-one mapping"""
32 return dict((key, val)
33 for keys, val in input_dict.items()
34 for key in keys)
35
36 LINESTYLES = _many_to_one({('solid', '-', (None, None)): 'none',
37 ('dashed', '--'): "6,6",
38 ('dotted', ':'): "2,2",
39 ('dashdot', '-.'): "4,4,2,4",
40 ('', ' ', 'None', 'none'): None})
41
42
43 def get_dasharray(obj):
44 """Get an SVG dash array for the given matplotlib linestyle
45
46 Parameters
47 ----------
48 obj : matplotlib object
49 The matplotlib line or path object, which must have a get_linestyle()
50 method which returns a valid matplotlib line code
51
52 Returns
53 -------
54 dasharray : string
55 The HTML/SVG dasharray code associated with the object.
56 """
57 if obj.__dict__.get('_dashSeq', None) is not None:
58 return ','.join(map(str, obj._dashSeq))
59 else:
60 ls = obj.get_linestyle()
61 dasharray = LINESTYLES.get(ls, 'not found')
62 if dasharray == 'not found':
63 warnings.warn("line style '{0}' not understood: "
64 "defaulting to solid line.".format(ls))
65 dasharray = LINESTYLES['solid']
66 return dasharray
67
68
69 PATH_DICT = {Path.LINETO: 'L',
70 Path.MOVETO: 'M',
71 Path.CURVE3: 'S',
72 Path.CURVE4: 'C',
73 Path.CLOSEPOLY: 'Z'}
74
75
76 def SVG_path(path, transform=None, simplify=False):
77 """Construct the vertices and SVG codes for the path
78
79 Parameters
80 ----------
81 path : matplotlib.Path object
82
83 transform : matplotlib transform (optional)
84 if specified, the path will be transformed before computing the output.
85
86 Returns
87 -------
88 vertices : array
89 The shape (M, 2) array of vertices of the Path. Note that some Path
90 codes require multiple vertices, so the length of these vertices may
91 be longer than the list of path codes.
92 path_codes : list
93 A length N list of single-character path codes, N <= M. Each code is
94 a single character, in ['L','M','S','C','Z']. See the standard SVG
95 path specification for a description of these.
96 """
97 if transform is not None:
98 path = path.transformed(transform)
99
100 vc_tuples = [(vertices if path_code != Path.CLOSEPOLY else [],
101 PATH_DICT[path_code])
102 for (vertices, path_code)
103 in path.iter_segments(simplify=simplify)]
104
105 if not vc_tuples:
106 # empty path is a special case
107 return np.zeros((0, 2)), []
108 else:
109 vertices, codes = zip(*vc_tuples)
110 vertices = np.array(list(itertools.chain(*vertices))).reshape(-1, 2)
111 return vertices, list(codes)
112
113
114 def get_path_style(path, fill=True):
115 """Get the style dictionary for matplotlib path objects"""
116 style = {}
117 style['alpha'] = path.get_alpha()
118 if style['alpha'] is None:
119 style['alpha'] = 1
120 style['edgecolor'] = color_to_hex(path.get_edgecolor())
121 if fill:
122 style['facecolor'] = color_to_hex(path.get_facecolor())
123 else:
124 style['facecolor'] = 'none'
125 style['edgewidth'] = path.get_linewidth()
126 style['dasharray'] = get_dasharray(path)
127 style['zorder'] = path.get_zorder()
128 return style
129
130
131 def get_line_style(line):
132 """Get the style dictionary for matplotlib line objects"""
133 style = {}
134 style['alpha'] = line.get_alpha()
135 if style['alpha'] is None:
136 style['alpha'] = 1
137 style['color'] = color_to_hex(line.get_color())
138 style['linewidth'] = line.get_linewidth()
139 style['dasharray'] = get_dasharray(line)
140 style['zorder'] = line.get_zorder()
141 return style
142
143
144 def get_marker_style(line):
145 """Get the style dictionary for matplotlib marker objects"""
146 style = {}
147 style['alpha'] = line.get_alpha()
148 if style['alpha'] is None:
149 style['alpha'] = 1
150
151 style['facecolor'] = color_to_hex(line.get_markerfacecolor())
152 style['edgecolor'] = color_to_hex(line.get_markeredgecolor())
153 style['edgewidth'] = line.get_markeredgewidth()
154
155 style['marker'] = line.get_marker()
156 markerstyle = MarkerStyle(line.get_marker())
157 markersize = line.get_markersize()
158 markertransform = (markerstyle.get_transform()
159 + Affine2D().scale(markersize, -markersize))
160 style['markerpath'] = SVG_path(markerstyle.get_path(),
161 markertransform)
162 style['markersize'] = markersize
163 style['zorder'] = line.get_zorder()
164 return style
165
166
167 def get_text_style(text):
168 """Return the text style dict for a text instance"""
169 style = {}
170 style['alpha'] = text.get_alpha()
171 if style['alpha'] is None:
172 style['alpha'] = 1
173 style['fontsize'] = text.get_size()
174 style['color'] = color_to_hex(text.get_color())
175 style['halign'] = text.get_horizontalalignment() # left, center, right
176 style['valign'] = text.get_verticalalignment() # baseline, center, top
177 style['malign'] = text._multialignment # text alignment when '\n' in text
178 style['rotation'] = text.get_rotation()
179 style['zorder'] = text.get_zorder()
180 return style
181
182
183 def get_axis_properties(axis):
184 """Return the property dictionary for a matplotlib.Axis instance"""
185 props = {}
186 label1On = axis._major_tick_kw.get('label1On', True)
187
188 if isinstance(axis, matplotlib.axis.XAxis):
189 if label1On:
190 props['position'] = "bottom"
191 else:
192 props['position'] = "top"
193 elif isinstance(axis, matplotlib.axis.YAxis):
194 if label1On:
195 props['position'] = "left"
196 else:
197 props['position'] = "right"
198 else:
199 raise ValueError("{0} should be an Axis instance".format(axis))
200
201 # Use tick values if appropriate
202 locator = axis.get_major_locator()
203 props['nticks'] = len(locator())
204 if isinstance(locator, ticker.FixedLocator):
205 props['tickvalues'] = list(locator())
206 else:
207 props['tickvalues'] = None
208
209 # Find tick formats
210 formatter = axis.get_major_formatter()
211 if isinstance(formatter, ticker.NullFormatter):
212 props['tickformat'] = ""
213 elif isinstance(formatter, ticker.FixedFormatter):
214 props['tickformat'] = list(formatter.seq)
215 elif not any(label.get_visible() for label in axis.get_ticklabels()):
216 props['tickformat'] = ""
217 else:
218 props['tickformat'] = None
219
220 # Get axis scale
221 props['scale'] = axis.get_scale()
222
223 # Get major tick label size (assumes that's all we really care about!)
224 labels = axis.get_ticklabels()
225 if labels:
226 props['fontsize'] = labels[0].get_fontsize()
227 else:
228 props['fontsize'] = None
229
230 # Get associated grid
231 props['grid'] = get_grid_style(axis)
232
233 return props
234
235
236 def get_grid_style(axis):
237 gridlines = axis.get_gridlines()
238 if axis._gridOnMajor and len(gridlines) > 0:
239 color = color_to_hex(gridlines[0].get_color())
240 alpha = gridlines[0].get_alpha()
241 dasharray = get_dasharray(gridlines[0])
242 return dict(gridOn=True,
243 color=color,
244 dasharray=dasharray,
245 alpha=alpha)
246 else:
247 return {"gridOn": False}
248
249
250 def get_figure_properties(fig):
251 return {'figwidth': fig.get_figwidth(),
252 'figheight': fig.get_figheight(),
253 'dpi': fig.dpi}
254
255
256 def get_axes_properties(ax):
257 props = {'axesbg': color_to_hex(ax.patch.get_facecolor()),
258 'axesbgalpha': ax.patch.get_alpha(),
259 'bounds': ax.get_position().bounds,
260 'dynamic': ax.get_navigate(),
261 'axison': ax.axison,
262 'frame_on': ax.get_frame_on(),
263 'axes': [get_axis_properties(ax.xaxis),
264 get_axis_properties(ax.yaxis)]}
265
266 for axname in ['x', 'y']:
267 axis = getattr(ax, axname + 'axis')
268 domain = getattr(ax, 'get_{0}lim'.format(axname))()
269 lim = domain
270 if isinstance(axis.converter, matplotlib.dates.DateConverter):
271 scale = 'date'
272 try:
273 import pandas as pd
274 from pandas.tseries.converter import PeriodConverter
275 except ImportError:
276 pd = None
277
278 if (pd is not None and isinstance(axis.converter,
279 PeriodConverter)):
280 _dates = [pd.Period(ordinal=int(d), freq=axis.freq)
281 for d in domain]
282 domain = [(d.year, d.month - 1, d.day,
283 d.hour, d.minute, d.second, 0)
284 for d in _dates]
285 else:
286 domain = [(d.year, d.month - 1, d.day,
287 d.hour, d.minute, d.second,
288 d.microsecond * 1E-3)
289 for d in matplotlib.dates.num2date(domain)]
290 else:
291 scale = axis.get_scale()
292
293 if scale not in ['date', 'linear', 'log']:
294 raise ValueError("Unknown axis scale: "
295 "{0}".format(axis[axname].get_scale()))
296
297 props[axname + 'scale'] = scale
298 props[axname + 'lim'] = lim
299 props[axname + 'domain'] = domain
300
301 return props
302
303
304 def iter_all_children(obj, skipContainers=False):
305 """
306 Returns an iterator over all childen and nested children using
307 obj's get_children() method
308
309 if skipContainers is true, only childless objects are returned.
310 """
311 if hasattr(obj, 'get_children') and len(obj.get_children()) > 0:
312 for child in obj.get_children():
313 if not skipContainers:
314 yield child
315 # could use `yield from` in python 3...
316 for grandchild in iter_all_children(child, skipContainers):
317 yield grandchild
318 else:
319 yield obj
320
321
322 def get_legend_properties(ax, legend):
323 handles, labels = ax.get_legend_handles_labels()
324 visible = legend.get_visible()
325 return {'handles': handles, 'labels': labels, 'visible': visible}
326
327
328 def image_to_base64(image):
329 """
330 Convert a matplotlib image to a base64 png representation
331
332 Parameters
333 ----------
334 image : matplotlib image object
335 The image to be converted.
336
337 Returns
338 -------
339 image_base64 : string
340 The UTF8-encoded base64 string representation of the png image.
341 """
342 ax = image.axes
343 binary_buffer = io.BytesIO()
344
345 # image is saved in axes coordinates: we need to temporarily
346 # set the correct limits to get the correct image
347 lim = ax.axis()
348 ax.axis(image.get_extent())
349 image.write_png(binary_buffer)
350 ax.axis(lim)
351
352 binary_buffer.seek(0)
353 return base64.b64encode(binary_buffer.read()).decode('utf-8')