Print a figure to an image, and return the resulting file data Returned data will be bytes unless ``fmt='svg'``, in which case it will be unicode. Any keyword args are passed to fig.canvas.print_figure, such as ``quality`` or ``bbox_inches``.
(fig, fmt='png', bbox_inches='tight', **kwargs)
| 95 | |
| 96 | |
| 97 | def print_figure(fig, fmt='png', bbox_inches='tight', **kwargs): |
| 98 | """Print a figure to an image, and return the resulting file data |
| 99 | |
| 100 | Returned data will be bytes unless ``fmt='svg'``, |
| 101 | in which case it will be unicode. |
| 102 | |
| 103 | Any keyword args are passed to fig.canvas.print_figure, |
| 104 | such as ``quality`` or ``bbox_inches``. |
| 105 | """ |
| 106 | # When there's an empty figure, we shouldn't return anything, otherwise we |
| 107 | # get big blank areas in the qt console. |
| 108 | if not fig.axes and not fig.lines: |
| 109 | return |
| 110 | |
| 111 | dpi = fig.dpi |
| 112 | if fmt == 'retina': |
| 113 | dpi = dpi * 2 |
| 114 | fmt = 'png' |
| 115 | |
| 116 | # build keyword args |
| 117 | kw = { |
| 118 | "format":fmt, |
| 119 | "facecolor":fig.get_facecolor(), |
| 120 | "edgecolor":fig.get_edgecolor(), |
| 121 | "dpi":dpi, |
| 122 | "bbox_inches":bbox_inches, |
| 123 | } |
| 124 | # **kwargs get higher priority |
| 125 | kw.update(kwargs) |
| 126 | |
| 127 | bytes_io = BytesIO() |
| 128 | if fig.canvas is None: |
| 129 | from matplotlib.backend_bases import FigureCanvasBase |
| 130 | FigureCanvasBase(fig) |
| 131 | |
| 132 | fig.canvas.print_figure(bytes_io, **kw) |
| 133 | data = bytes_io.getvalue() |
| 134 | if fmt == 'svg': |
| 135 | data = data.decode('utf-8') |
| 136 | return data |
| 137 | |
| 138 | def retina_figure(fig, **kwargs): |
| 139 | """format a figure as a pixel-doubled (retina) PNG""" |
no test coverage detected