Debian Codegraph @

mplexporter/renderers/base.py

raw symbols SCIP
1 import warnings
2 import itertools
3 from contextlib import contextmanager
4
5 import numpy as np
6 from matplotlib import transforms
7
8 from .. import utils
9 from .. import _py3k_compat as py3k
10
11
12 class Renderer(object):
13 @staticmethod
14 def ax_zoomable(ax):
15 return bool(ax and ax.get_navigate())
16
17 @staticmethod
18 def ax_has_xgrid(ax):
19 return bool(ax and ax.xaxis._gridOnMajor and ax.yaxis.get_gridlines())
20
21 @staticmethod
22 def ax_has_ygrid(ax):
23 return bool(ax and ax.yaxis._gridOnMajor and ax.yaxis.get_gridlines())
24
25 @property
26 def current_ax_zoomable(self):
27 return self.ax_zoomable(self._current_ax)
28
29 @property
30 def current_ax_has_xgrid(self):
31 return self.ax_has_xgrid(self._current_ax)
32
33 @property
34 def current_ax_has_ygrid(self):
35 return self.ax_has_ygrid(self._current_ax)
36
37 @contextmanager
38 def draw_figure(self, fig, props):
39 if hasattr(self, "_current_fig") and self._current_fig is not None:
40 warnings.warn("figure embedded in figure: something is wrong")
41 self._current_fig = fig
42 self._fig_props = props
43 self.open_figure(fig=fig, props=props)
44 yield
45 self.close_figure(fig=fig)
46 self._current_fig = None
47 self._fig_props = {}
48
49 @contextmanager
50 def draw_axes(self, ax, props):
51 if hasattr(self, "_current_ax") and self._current_ax is not None:
52 warnings.warn("axes embedded in axes: something is wrong")
53 self._current_ax = ax
54 self._ax_props = props
55 self.open_axes(ax=ax, props=props)
56 yield
57 self.close_axes(ax=ax)
58 self._current_ax = None
59 self._ax_props = {}
60
61 @contextmanager
62 def draw_legend(self, legend, props):
63 self._current_legend = legend
64 self._legend_props = props
65 self.open_legend(legend=legend, props=props)
66 yield
67 self.close_legend(legend=legend)
68 self._current_legend = None
69 self._legend_props = {}
70
71 # Following are the functions which should be overloaded in subclasses
72
73 def open_figure(self, fig, props):
74 """
75 Begin commands for a particular figure.
76
77 Parameters
78 ----------
79 fig : matplotlib.Figure
80 The Figure which will contain the ensuing axes and elements
81 props : dictionary
82 The dictionary of figure properties
83 """
84 pass
85
86 def close_figure(self, fig):
87 """
88 Finish commands for a particular figure.
89
90 Parameters
91 ----------
92 fig : matplotlib.Figure
93 The figure which is finished being drawn.
94 """
95 pass
96
97 def open_axes(self, ax, props):
98 """
99 Begin commands for a particular axes.
100
101 Parameters
102 ----------
103 ax : matplotlib.Axes
104 The Axes which will contain the ensuing axes and elements
105 props : dictionary
106 The dictionary of axes properties
107 """
108 pass
109
110 def close_axes(self, ax):
111 """
112 Finish commands for a particular axes.
113
114 Parameters
115 ----------
116 ax : matplotlib.Axes
117 The Axes which is finished being drawn.
118 """
119 pass
120
121 def open_legend(self, legend, props):
122 """
123 Beging commands for a particular legend.
124
125 Parameters
126 ----------
127 legend : matplotlib.legend.Legend
128 The Legend that will contain the ensuing elements
129 props : dictionary
130 The dictionary of legend properties
131 """
132 pass
133
134 def close_legend(self, legend):
135 """
136 Finish commands for a particular legend.
137
138 Parameters
139 ----------
140 legend : matplotlib.legend.Legend
141 The Legend which is finished being drawn
142 """
143 pass
144
145 def draw_marked_line(self, data, coordinates, linestyle, markerstyle,
146 label, mplobj=None):
147 """Draw a line that also has markers.
148
149 If this isn't reimplemented by a renderer object, by default, it will
150 make a call to BOTH draw_line and draw_markers when both markerstyle
151 and linestyle are not None in the same Line2D object.
152
153 """
154 if linestyle is not None:
155 self.draw_line(data, coordinates, linestyle, label, mplobj)
156 if markerstyle is not None:
157 self.draw_markers(data, coordinates, markerstyle, label, mplobj)
158
159 def draw_line(self, data, coordinates, style, label, mplobj=None):
160 """
161 Draw a line. By default, draw the line via the draw_path() command.
162 Some renderers might wish to override this and provide more
163 fine-grained behavior.
164
165 In matplotlib, lines are generally created via the plt.plot() command,
166 though this command also can create marker collections.
167
168 Parameters
169 ----------
170 data : array_like
171 A shape (N, 2) array of datapoints.
172 coordinates : string
173 A string code, which should be either 'data' for data coordinates,
174 or 'figure' for figure (pixel) coordinates.
175 style : dictionary
176 a dictionary specifying the appearance of the line.
177 mplobj : matplotlib object
178 the matplotlib plot element which generated this line
179 """
180 pathcodes = ['M'] + (data.shape[0] - 1) * ['L']
181 pathstyle = dict(facecolor='none', **style)
182 pathstyle['edgecolor'] = pathstyle.pop('color')
183 pathstyle['edgewidth'] = pathstyle.pop('linewidth')
184 self.draw_path(data=data, coordinates=coordinates,
185 pathcodes=pathcodes, style=pathstyle, mplobj=mplobj)
186
187 @staticmethod
188 def _iter_path_collection(paths, path_transforms, offsets, styles):
189 """Build an iterator over the elements of the path collection"""
190 N = max(len(paths), len(offsets))
191
192 if not path_transforms:
193 path_transforms = [np.eye(3)]
194
195 edgecolor = styles['edgecolor']
196 if np.size(edgecolor) == 0:
197 edgecolor = ['none']
198 facecolor = styles['facecolor']
199 if np.size(facecolor) == 0:
200 facecolor = ['none']
201
202 elements = [paths, path_transforms, offsets,
203 edgecolor, styles['linewidth'], facecolor]
204
205 it = itertools
206 return it.islice(py3k.zip(*py3k.map(it.cycle, elements)), N)
207
208 def draw_path_collection(self, paths, path_coordinates, path_transforms,
209 offsets, offset_coordinates, offset_order,
210 styles, mplobj=None):
211 """
212 Draw a collection of paths. The paths, offsets, and styles are all
213 iterables, and the number of paths is max(len(paths), len(offsets)).
214
215 By default, this is implemented via multiple calls to the draw_path()
216 function. For efficiency, Renderers may choose to customize this
217 implementation.
218
219 Examples of path collections created by matplotlib are scatter plots,
220 histograms, contour plots, and many others.
221
222 Parameters
223 ----------
224 paths : list
225 list of tuples, where each tuple has two elements:
226 (data, pathcodes). See draw_path() for a description of these.
227 path_coordinates: string
228 the coordinates code for the paths, which should be either
229 'data' for data coordinates, or 'figure' for figure (pixel)
230 coordinates.
231 path_transforms: array_like
232 an array of shape (*, 3, 3), giving a series of 2D Affine
233 transforms for the paths. These encode translations, rotations,
234 and scalings in the standard way.
235 offsets: array_like
236 An array of offsets of shape (N, 2)
237 offset_coordinates : string
238 the coordinates code for the offsets, which should be either
239 'data' for data coordinates, or 'figure' for figure (pixel)
240 coordinates.
241 offset_order : string
242 either "before" or "after". This specifies whether the offset
243 is applied before the path transform, or after. The matplotlib
244 backend equivalent is "before"->"data", "after"->"screen".
245 styles: dictionary
246 A dictionary in which each value is a list of length N, containing
247 the style(s) for the paths.
248 mplobj : matplotlib object
249 the matplotlib plot element which generated this collection
250 """
251 if offset_order == "before":
252 raise NotImplementedError("offset before transform")
253
254 for tup in self._iter_path_collection(paths, path_transforms,
255 offsets, styles):
256 (path, path_transform, offset, ec, lw, fc) = tup
257 vertices, pathcodes = path
258 path_transform = transforms.Affine2D(path_transform)
259 vertices = path_transform.transform(vertices)
260 # This is a hack:
261 if path_coordinates == "figure":
262 path_coordinates = "points"
263 style = {"edgecolor": utils.color_to_hex(ec),
264 "facecolor": utils.color_to_hex(fc),
265 "edgewidth": lw,
266 "dasharray": "10,0",
267 "alpha": styles['alpha'],
268 "zorder": styles['zorder']}
269 self.draw_path(data=vertices, coordinates=path_coordinates,
270 pathcodes=pathcodes, style=style, offset=offset,
271 offset_coordinates=offset_coordinates,
272 mplobj=mplobj)
273
274 def draw_markers(self, data, coordinates, style, label, mplobj=None):
275 """
276 Draw a set of markers. By default, this is done by repeatedly
277 calling draw_path(), but renderers should generally overload
278 this method to provide a more efficient implementation.
279
280 In matplotlib, markers are created using the plt.plot() command.
281
282 Parameters
283 ----------
284 data : array_like
285 A shape (N, 2) array of datapoints.
286 coordinates : string
287 A string code, which should be either 'data' for data coordinates,
288 or 'figure' for figure (pixel) coordinates.
289 style : dictionary
290 a dictionary specifying the appearance of the markers.
291 mplobj : matplotlib object
292 the matplotlib plot element which generated this marker collection
293 """
294 vertices, pathcodes = style['markerpath']
295 pathstyle = dict((key, style[key]) for key in ['alpha', 'edgecolor',
296 'facecolor', 'zorder',
297 'edgewidth'])
298 pathstyle['dasharray'] = "10,0"
299 for vertex in data:
300 self.draw_path(data=vertices, coordinates="points",
301 pathcodes=pathcodes, style=pathstyle,
302 offset=vertex, offset_coordinates=coordinates,
303 mplobj=mplobj)
304
305 def draw_text(self, text, position, coordinates, style,
306 text_type=None, mplobj=None):
307 """
308 Draw text on the image.
309
310 Parameters
311 ----------
312 text : string
313 The text to draw
314 position : tuple
315 The (x, y) position of the text
316 coordinates : string
317 A string code, which should be either 'data' for data coordinates,
318 or 'figure' for figure (pixel) coordinates.
319 style : dictionary
320 a dictionary specifying the appearance of the text.
321 text_type : string or None
322 if specified, a type of text such as "xlabel", "ylabel", "title"
323 mplobj : matplotlib object
324 the matplotlib plot element which generated this text
325 """
326 raise NotImplementedError()
327
328 def draw_path(self, data, coordinates, pathcodes, style,
329 offset=None, offset_coordinates="data", mplobj=None):
330 """
331 Draw a path.
332
333 In matplotlib, paths are created by filled regions, histograms,
334 contour plots, patches, etc.
335
336 Parameters
337 ----------
338 data : array_like
339 A shape (N, 2) array of datapoints.
340 coordinates : string
341 A string code, which should be either 'data' for data coordinates,
342 'figure' for figure (pixel) coordinates, or "points" for raw
343 point coordinates (useful in conjunction with offsets, below).
344 pathcodes : list
345 A list of single-character SVG pathcodes associated with the data.
346 Path codes are one of ['M', 'm', 'L', 'l', 'Q', 'q', 'T', 't',
347 'S', 's', 'C', 'c', 'Z', 'z']
348 See the SVG specification for details. Note that some path codes
349 consume more than one datapoint (while 'Z' consumes none), so
350 in general, the length of the pathcodes list will not be the same
351 as that of the data array.
352 style : dictionary
353 a dictionary specifying the appearance of the line.
354 offset : list (optional)
355 the (x, y) offset of the path. If not given, no offset will
356 be used.
357 offset_coordinates : string (optional)
358 A string code, which should be either 'data' for data coordinates,
359 or 'figure' for figure (pixel) coordinates.
360 mplobj : matplotlib object
361 the matplotlib plot element which generated this path
362 """
363 raise NotImplementedError()
364
365 def draw_image(self, imdata, extent, coordinates, style, mplobj=None):
366 """
367 Draw an image.
368
369 Parameters
370 ----------
371 imdata : string
372 base64 encoded png representation of the image
373 extent : list
374 the axes extent of the image: [xmin, xmax, ymin, ymax]
375 coordinates: string
376 A string code, which should be either 'data' for data coordinates,
377 or 'figure' for figure (pixel) coordinates.
378 style : dictionary
379 a dictionary specifying the appearance of the image
380 mplobj : matplotlib object
381 the matplotlib plot object which generated this image
382 """
383 raise NotImplementedError()