| 1 |
""" |
| 2 |
Matplotlib Exporter |
| 3 |
=================== |
| 4 |
This submodule contains tools for crawling a matplotlib figure and exporting |
| 5 |
relevant pieces to a renderer. |
| 6 |
""" |
| 7 |
import warnings |
| 8 |
import io |
| 9 |
from . import utils |
| 10 |
|
| 11 |
import matplotlib |
| 12 |
from matplotlib import transforms, collections |
| 13 |
from matplotlib.backends.backend_agg import FigureCanvasAgg |
| 14 |
|
| 15 |
class Exporter(object): |
| 16 |
"""Matplotlib Exporter |
| 17 |
|
| 18 |
Parameters |
| 19 |
---------- |
| 20 |
renderer : Renderer object |
| 21 |
The renderer object called by the exporter to create a figure |
| 22 |
visualization. See mplexporter.Renderer for information on the |
| 23 |
methods which should be defined within the renderer. |
| 24 |
close_mpl : bool |
| 25 |
If True (default), close the matplotlib figure as it is rendered. This |
| 26 |
is useful for when the exporter is used within the notebook, or with |
| 27 |
an interactive matplotlib backend. |
| 28 |
""" |
| 29 |
|
| 30 |
def __init__(self, renderer, close_mpl=True): |
| 31 |
self.close_mpl = close_mpl |
| 32 |
self.renderer = renderer |
| 33 |
|
| 34 |
def run(self, fig): |
| 35 |
""" |
| 36 |
Run the exporter on the given figure |
| 37 |
|
| 38 |
Parmeters |
| 39 |
--------- |
| 40 |
fig : matplotlib.Figure instance |
| 41 |
The figure to export |
| 42 |
""" |
| 43 |
|
| 44 |
|
| 45 |
if fig.canvas is None: |
| 46 |
canvas = FigureCanvasAgg(fig) |
| 47 |
fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi) |
| 48 |
if self.close_mpl: |
| 49 |
import matplotlib.pyplot as plt |
| 50 |
plt.close(fig) |
| 51 |
self.crawl_fig(fig) |
| 52 |
|
| 53 |
@staticmethod |
| 54 |
def process_transform(transform, ax=None, data=None, return_trans=False, |
| 55 |
force_trans=None): |
| 56 |
"""Process the transform and convert data to figure or data coordinates |
| 57 |
|
| 58 |
Parameters |
| 59 |
---------- |
| 60 |
transform : matplotlib Transform object |
| 61 |
The transform applied to the data |
| 62 |
ax : matplotlib Axes object (optional) |
| 63 |
The axes the data is associated with |
| 64 |
data : ndarray (optional) |
| 65 |
The array of data to be transformed. |
| 66 |
return_trans : bool (optional) |
| 67 |
If true, return the final transform of the data |
| 68 |
force_trans : matplotlib.transform instance (optional) |
| 69 |
If supplied, first force the data to this transform |
| 70 |
|
| 71 |
Returns |
| 72 |
------- |
| 73 |
code : string |
| 74 |
Code is either "data", "axes", "figure", or "display", indicating |
| 75 |
the type of coordinates output. |
| 76 |
transform : matplotlib transform |
| 77 |
the transform used to map input data to output data. |
| 78 |
Returned only if return_trans is True |
| 79 |
new_data : ndarray |
| 80 |
Data transformed to match the given coordinate code. |
| 81 |
Returned only if data is specified |
| 82 |
""" |
| 83 |
if isinstance(transform, transforms.BlendedGenericTransform): |
| 84 |
warnings.warn("Blended transforms not yet supported. " |
| 85 |
"Zoom behavior may not work as expected.") |
| 86 |
|
| 87 |
if force_trans is not None: |
| 88 |
if data is not None: |
| 89 |
data = (transform - force_trans).transform(data) |
| 90 |
transform = force_trans |
| 91 |
|
| 92 |
code = "display" |
| 93 |
if ax is not None: |
| 94 |
for (c, trans) in [("data", ax.transData), |
| 95 |
("axes", ax.transAxes), |
| 96 |
("figure", ax.figure.transFigure), |
| 97 |
("display", transforms.IdentityTransform())]: |
| 98 |
if transform.contains_branch(trans): |
| 99 |
code, transform = (c, transform - trans) |
| 100 |
break |
| 101 |
|
| 102 |
if data is not None: |
| 103 |
if return_trans: |
| 104 |
return code, transform.transform(data), transform |
| 105 |
else: |
| 106 |
return code, transform.transform(data) |
| 107 |
else: |
| 108 |
if return_trans: |
| 109 |
return code, transform |
| 110 |
else: |
| 111 |
return code |
| 112 |
|
| 113 |
def crawl_fig(self, fig): |
| 114 |
"""Crawl the figure and process all axes""" |
| 115 |
with self.renderer.draw_figure(fig=fig, |
| 116 |
props=utils.get_figure_properties(fig)): |
| 117 |
for ax in fig.axes: |
| 118 |
self.crawl_ax(ax) |
| 119 |
|
| 120 |
def crawl_ax(self, ax): |
| 121 |
"""Crawl the axes and process all elements within""" |
| 122 |
with self.renderer.draw_axes(ax=ax, |
| 123 |
props=utils.get_axes_properties(ax)): |
| 124 |
for line in ax.lines: |
| 125 |
self.draw_line(ax, line) |
| 126 |
for text in ax.texts: |
| 127 |
self.draw_text(ax, text) |
| 128 |
for (text, ttp) in zip([ax.xaxis.label, ax.yaxis.label, ax.title], |
| 129 |
["xlabel", "ylabel", "title"]): |
| 130 |
if(hasattr(text, 'get_text') and text.get_text()): |
| 131 |
self.draw_text(ax, text, force_trans=ax.transAxes, |
| 132 |
text_type=ttp) |
| 133 |
for artist in ax.artists: |
| 134 |
|
| 135 |
if isinstance(artist, matplotlib.text.Text): |
| 136 |
self.draw_text(ax, artist) |
| 137 |
for patch in ax.patches: |
| 138 |
self.draw_patch(ax, patch) |
| 139 |
for collection in ax.collections: |
| 140 |
self.draw_collection(ax, collection) |
| 141 |
for image in ax.images: |
| 142 |
self.draw_image(ax, image) |
| 143 |
|
| 144 |
legend = ax.get_legend() |
| 145 |
if legend is not None: |
| 146 |
props = utils.get_legend_properties(ax, legend) |
| 147 |
with self.renderer.draw_legend(legend=legend, props=props): |
| 148 |
if props['visible']: |
| 149 |
self.crawl_legend(ax, legend) |
| 150 |
|
| 151 |
def crawl_legend(self, ax, legend): |
| 152 |
""" |
| 153 |
Recursively look through objects in legend children |
| 154 |
""" |
| 155 |
legendElements = list(utils.iter_all_children(legend._legend_box, |
| 156 |
skipContainers=True)) |
| 157 |
legendElements.append(legend.legendPatch) |
| 158 |
for child in legendElements: |
| 159 |
|
| 160 |
child.set_zorder(1E6 + child.get_zorder()) |
| 161 |
|
| 162 |
try: |
| 163 |
|
| 164 |
if isinstance(child, matplotlib.patches.Patch): |
| 165 |
self.draw_patch(ax, child, force_trans=ax.transAxes) |
| 166 |
elif isinstance(child, matplotlib.text.Text): |
| 167 |
if not (child is legend.get_children()[-1] |
| 168 |
and child.get_text() == 'None'): |
| 169 |
self.draw_text(ax, child, force_trans=ax.transAxes) |
| 170 |
elif isinstance(child, matplotlib.lines.Line2D): |
| 171 |
self.draw_line(ax, child, force_trans=ax.transAxes) |
| 172 |
elif isinstance(child, matplotlib.collections.Collection): |
| 173 |
self.draw_collection(ax, child, |
| 174 |
force_pathtrans=ax.transAxes) |
| 175 |
else: |
| 176 |
warnings.warn("Legend element %s not impemented" % child) |
| 177 |
except NotImplementedError: |
| 178 |
warnings.warn("Legend element %s not impemented" % child) |
| 179 |
|
| 180 |
def draw_line(self, ax, line, force_trans=None): |
| 181 |
"""Process a matplotlib line and call renderer.draw_line""" |
| 182 |
coordinates, data = self.process_transform(line.get_transform(), |
| 183 |
ax, line.get_xydata(), |
| 184 |
force_trans=force_trans) |
| 185 |
linestyle = utils.get_line_style(line) |
| 186 |
if linestyle['dasharray'] is None: |
| 187 |
linestyle = None |
| 188 |
markerstyle = utils.get_marker_style(line) |
| 189 |
if (markerstyle['marker'] in ['None', 'none', None] |
| 190 |
or markerstyle['markerpath'][0].size == 0): |
| 191 |
markerstyle = None |
| 192 |
label = line.get_label() |
| 193 |
if markerstyle or linestyle: |
| 194 |
self.renderer.draw_marked_line(data=data, coordinates=coordinates, |
| 195 |
linestyle=linestyle, |
| 196 |
markerstyle=markerstyle, |
| 197 |
label=label, |
| 198 |
mplobj=line) |
| 199 |
|
| 200 |
def draw_text(self, ax, text, force_trans=None, text_type=None): |
| 201 |
"""Process a matplotlib text object and call renderer.draw_text""" |
| 202 |
content = text.get_text() |
| 203 |
if content: |
| 204 |
transform = text.get_transform() |
| 205 |
position = text.get_position() |
| 206 |
coords, position = self.process_transform(transform, ax, |
| 207 |
position, |
| 208 |
force_trans=force_trans) |
| 209 |
style = utils.get_text_style(text) |
| 210 |
self.renderer.draw_text(text=content, position=position, |
| 211 |
coordinates=coords, |
| 212 |
text_type=text_type, |
| 213 |
style=style, mplobj=text) |
| 214 |
|
| 215 |
def draw_patch(self, ax, patch, force_trans=None): |
| 216 |
"""Process a matplotlib patch object and call renderer.draw_path""" |
| 217 |
vertices, pathcodes = utils.SVG_path(patch.get_path()) |
| 218 |
transform = patch.get_transform() |
| 219 |
coordinates, vertices = self.process_transform(transform, |
| 220 |
ax, vertices, |
| 221 |
force_trans=force_trans) |
| 222 |
linestyle = utils.get_path_style(patch, fill=patch.get_fill()) |
| 223 |
self.renderer.draw_path(data=vertices, |
| 224 |
coordinates=coordinates, |
| 225 |
pathcodes=pathcodes, |
| 226 |
style=linestyle, |
| 227 |
mplobj=patch) |
| 228 |
|
| 229 |
def draw_collection(self, ax, collection, |
| 230 |
force_pathtrans=None, |
| 231 |
force_offsettrans=None): |
| 232 |
"""Process a matplotlib collection and call renderer.draw_collection""" |
| 233 |
(transform, transOffset, |
| 234 |
offsets, paths) = collection._prepare_points() |
| 235 |
|
| 236 |
offset_coords, offsets = self.process_transform( |
| 237 |
transOffset, ax, offsets, force_trans=force_offsettrans) |
| 238 |
path_coords = self.process_transform( |
| 239 |
transform, ax, force_trans=force_pathtrans) |
| 240 |
|
| 241 |
processed_paths = [utils.SVG_path(path) for path in paths] |
| 242 |
processed_paths = [(self.process_transform( |
| 243 |
transform, ax, path[0], force_trans=force_pathtrans)[1], path[1]) |
| 244 |
for path in processed_paths] |
| 245 |
|
| 246 |
path_transforms = collection.get_transforms() |
| 247 |
try: |
| 248 |
|
| 249 |
|
| 250 |
path_transforms = [t.get_matrix() for t in path_transforms] |
| 251 |
except AttributeError: |
| 252 |
|
| 253 |
pass |
| 254 |
|
| 255 |
styles = {'linewidth': collection.get_linewidths(), |
| 256 |
'facecolor': collection.get_facecolors(), |
| 257 |
'edgecolor': collection.get_edgecolors(), |
| 258 |
'alpha': collection._alpha, |
| 259 |
'zorder': collection.get_zorder()} |
| 260 |
|
| 261 |
offset_dict = {"data": "before", |
| 262 |
"screen": "after"} |
| 263 |
offset_order = offset_dict[collection.get_offset_position()] |
| 264 |
|
| 265 |
self.renderer.draw_path_collection(paths=processed_paths, |
| 266 |
path_coordinates=path_coords, |
| 267 |
path_transforms=path_transforms, |
| 268 |
offsets=offsets, |
| 269 |
offset_coordinates=offset_coords, |
| 270 |
offset_order=offset_order, |
| 271 |
styles=styles, |
| 272 |
mplobj=collection) |
| 273 |
|
| 274 |
def draw_image(self, ax, image): |
| 275 |
"""Process a matplotlib image object and call renderer.draw_image""" |
| 276 |
self.renderer.draw_image(imdata=utils.image_to_base64(image), |
| 277 |
extent=image.get_extent(), |
| 278 |
coordinates="data", |
| 279 |
style={"alpha": image.get_alpha(), |
| 280 |
"zorder": image.get_zorder()}, |
| 281 |
mplobj=image) |