Show More
@@ -1,203 +1,224 b'' | |||
|
1 | 1 | """Produce SVG versions of active plots for display by the rich Qt frontend. |
|
2 | 2 | """ |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Imports |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | from __future__ import print_function |
|
7 | 7 | |
|
8 | 8 | # Standard library imports |
|
9 | 9 | import sys |
|
10 | 10 | |
|
11 | 11 | # Third-party imports |
|
12 | 12 | import matplotlib |
|
13 | 13 | from matplotlib.backends.backend_agg import new_figure_manager |
|
14 | 14 | from matplotlib._pylab_helpers import Gcf |
|
15 | 15 | |
|
16 | 16 | # Local imports. |
|
17 | 17 | from IPython.config.configurable import SingletonConfigurable |
|
18 | 18 | from IPython.core.displaypub import publish_display_data |
|
19 | 19 | from IPython.core.pylabtools import print_figure, select_figure_format |
|
20 | 20 | from IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, CBool |
|
21 | 21 | from IPython.utils.warn import warn |
|
22 | 22 | |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | # Configurable for inline backend options |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | # inherit from InlineBackendConfig for deprecation purposes |
|
27 | 27 | class InlineBackendConfig(SingletonConfigurable): |
|
28 | 28 | pass |
|
29 | 29 | |
|
30 | 30 | class InlineBackend(InlineBackendConfig): |
|
31 | 31 | """An object to store configuration of the inline backend.""" |
|
32 | 32 | |
|
33 | 33 | def _config_changed(self, name, old, new): |
|
34 | 34 | # warn on change of renamed config section |
|
35 | 35 | if new.InlineBackendConfig != old.InlineBackendConfig: |
|
36 | 36 | warn("InlineBackendConfig has been renamed to InlineBackend") |
|
37 | 37 | super(InlineBackend, self)._config_changed(name, old, new) |
|
38 | 38 | |
|
39 | 39 | # The typical default figure size is too large for inline use, |
|
40 | 40 | # so we shrink the figure size to 6x4, and tweak fonts to |
|
41 | 41 | # make that fit. |
|
42 | 42 | rc = Dict({'figure.figsize': (6.0,4.0), |
|
43 | 43 | # 12pt labels get cutoff on 6x4 logplots, so use 10pt. |
|
44 | 44 | 'font.size': 10, |
|
45 | 45 | # 72 dpi matches SVG/qtconsole |
|
46 | 46 | # this only affects PNG export, as SVG has no dpi setting |
|
47 | 47 | 'savefig.dpi': 72, |
|
48 | 48 | # 10pt still needs a little more room on the xlabel: |
|
49 | 49 | 'figure.subplot.bottom' : .125 |
|
50 | 50 | }, config=True, |
|
51 | 51 | help="""Subset of matplotlib rcParams that should be different for the |
|
52 | 52 | inline backend.""" |
|
53 | 53 | ) |
|
54 | 54 | |
|
55 | 55 | figure_format = CaselessStrEnum(['svg', 'png'], default_value='png', config=True, |
|
56 | 56 | help="The image format for figures with the inline backend.") |
|
57 | 57 | |
|
58 | 58 | def _figure_format_changed(self, name, old, new): |
|
59 | 59 | if self.shell is None: |
|
60 | 60 | return |
|
61 | 61 | else: |
|
62 | 62 | select_figure_format(self.shell, new) |
|
63 | 63 | |
|
64 | 64 | close_figures = CBool(True, config=True, |
|
65 | 65 | help="""Close all figures at the end of each cell. |
|
66 | 66 | |
|
67 | 67 | When True, ensures that each cell starts with no active figures, but it |
|
68 | 68 | also means that one must keep track of references in order to edit or |
|
69 | 69 | redraw figures in subsequent cells. This mode is ideal for the notebook, |
|
70 | 70 | where residual plots from other cells might be surprising. |
|
71 | 71 | |
|
72 | 72 | When False, one must call figure() to create new figures. This means |
|
73 | 73 | that gcf() and getfigs() can reference figures created in other cells, |
|
74 | 74 | and the active figure can continue to be edited with pylab/pyplot |
|
75 | 75 | methods that reference the current active figure. This mode facilitates |
|
76 | 76 | iterative editing of figures, and behaves most consistently with |
|
77 | 77 | other matplotlib backends, but figure barriers between cells must |
|
78 | 78 | be explicit. |
|
79 | 79 | """) |
|
80 | 80 | |
|
81 | 81 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
82 | 82 | |
|
83 | 83 | |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | # Functions |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | |
|
88 | 88 | def show(close=None): |
|
89 | 89 | """Show all figures as SVG/PNG payloads sent to the IPython clients. |
|
90 | 90 | |
|
91 | 91 | Parameters |
|
92 | 92 | ---------- |
|
93 | 93 | close : bool, optional |
|
94 | 94 | If true, a ``plt.close('all')`` call is automatically issued after |
|
95 | 95 | sending all the figures. If this is set, the figures will entirely |
|
96 | 96 | removed from the internal list of figures. |
|
97 | 97 | """ |
|
98 | 98 | if close is None: |
|
99 | 99 | close = InlineBackend.instance().close_figures |
|
100 | 100 | try: |
|
101 | 101 | for figure_manager in Gcf.get_all_fig_managers(): |
|
102 | 102 | send_figure(figure_manager.canvas.figure) |
|
103 | 103 | finally: |
|
104 | 104 | show._to_draw = [] |
|
105 | 105 | if close: |
|
106 | 106 | matplotlib.pyplot.close('all') |
|
107 | 107 | |
|
108 | 108 | |
|
109 | 109 | |
|
110 | 110 | # This flag will be reset by draw_if_interactive when called |
|
111 | 111 | show._draw_called = False |
|
112 | 112 | # list of figures to draw when flush_figures is called |
|
113 | 113 | show._to_draw = [] |
|
114 | 114 | |
|
115 | 115 | |
|
116 | 116 | def draw_if_interactive(): |
|
117 | 117 | """ |
|
118 | 118 | Is called after every pylab drawing command |
|
119 | 119 | """ |
|
120 |
# signal that the current active figure should be sent at the end of |
|
|
121 |
# Also sets the _draw_called flag, signaling that there will be |
|
|
122 |
# At the end of the code execution, a separate call to |
|
|
123 | # will act upon these values | |
|
124 | ||
|
120 | # signal that the current active figure should be sent at the end of | |
|
121 | # execution. Also sets the _draw_called flag, signaling that there will be | |
|
122 | # something to send. At the end of the code execution, a separate call to | |
|
123 | # flush_figures() will act upon these values | |
|
124 | ||
|
125 | 125 | fig = Gcf.get_active().canvas.figure |
|
126 | ||
|
127 | # Hack: matplotlib FigureManager objects in interacive backends (at least | |
|
128 | # in some of them) monkeypatch the figure object and add a .show() method | |
|
129 | # to it. This applies the same monkeypatch in order to support user code | |
|
130 | # that might expect `.show()` to be part of the official API of figure | |
|
131 | # objects. | |
|
132 | # For further reference: | |
|
133 | # https://github.com/ipython/ipython/issues/1612 | |
|
134 | # https://github.com/matplotlib/matplotlib/issues/835 | |
|
126 | 135 | |
|
136 | if not hasattr(fig, 'show'): | |
|
137 | # Queue up `fig` for display | |
|
138 | fig.show = lambda *a: send_figure(fig) | |
|
139 | ||
|
140 | # If matplotlib was manually set to non-interactive mode, this function | |
|
141 | # should be a no-op (otherwise we'll generate duplicate plots, since a user | |
|
142 | # who set ioff() manually expects to make separate draw/show calls). | |
|
143 | if not matplotlib.is_interactive(): | |
|
144 | return | |
|
145 | ||
|
127 | 146 | # ensure current figure will be drawn, and each subsequent call |
|
128 | 147 | # of draw_if_interactive() moves the active figure to ensure it is |
|
129 | 148 | # drawn last |
|
130 | 149 | try: |
|
131 | 150 | show._to_draw.remove(fig) |
|
132 | 151 | except ValueError: |
|
133 | 152 | # ensure it only appears in the draw list once |
|
134 | 153 | pass |
|
154 | # Queue up the figure for drawing in next show() call | |
|
135 | 155 | show._to_draw.append(fig) |
|
136 | 156 | show._draw_called = True |
|
137 | 157 | |
|
158 | ||
|
138 | 159 | def flush_figures(): |
|
139 | 160 | """Send all figures that changed |
|
140 | 161 | |
|
141 | 162 | This is meant to be called automatically and will call show() if, during |
|
142 | 163 | prior code execution, there had been any calls to draw_if_interactive. |
|
143 | 164 | |
|
144 | 165 | This function is meant to be used as a post_execute callback in IPython, |
|
145 | 166 | so user-caused errors are handled with showtraceback() instead of being |
|
146 | 167 | allowed to raise. If this function is not called from within IPython, |
|
147 | 168 | then these exceptions will raise. |
|
148 | 169 | """ |
|
149 | 170 | if not show._draw_called: |
|
150 | 171 | return |
|
151 | 172 | |
|
152 | 173 | if InlineBackend.instance().close_figures: |
|
153 | 174 | # ignore the tracking, just draw and close all figures |
|
154 | 175 | try: |
|
155 | 176 | return show(True) |
|
156 | 177 | except Exception as e: |
|
157 | 178 | # safely show traceback if in IPython, else raise |
|
158 | 179 | try: |
|
159 | 180 | get_ipython |
|
160 | 181 | except NameError: |
|
161 | 182 | raise e |
|
162 | 183 | else: |
|
163 | 184 | get_ipython().showtraceback() |
|
164 | 185 | return |
|
165 | 186 | try: |
|
166 | 187 | # exclude any figures that were closed: |
|
167 | 188 | active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()]) |
|
168 | 189 | for fig in [ fig for fig in show._to_draw if fig in active ]: |
|
169 | 190 | try: |
|
170 | 191 | send_figure(fig) |
|
171 | 192 | except Exception as e: |
|
172 | 193 | # safely show traceback if in IPython, else raise |
|
173 | 194 | try: |
|
174 | 195 | get_ipython |
|
175 | 196 | except NameError: |
|
176 | 197 | raise e |
|
177 | 198 | else: |
|
178 | 199 | get_ipython().showtraceback() |
|
179 | 200 | break |
|
180 | 201 | finally: |
|
181 | 202 | # clear flags for next round |
|
182 | 203 | show._to_draw = [] |
|
183 | 204 | show._draw_called = False |
|
184 | 205 | |
|
185 | 206 | |
|
186 | 207 | def send_figure(fig): |
|
187 |
"""Draw the |
|
|
208 | """Draw the given figure and send it as a PNG payload. | |
|
188 | 209 | """ |
|
189 | 210 | fmt = InlineBackend.instance().figure_format |
|
190 | 211 | data = print_figure(fig, fmt) |
|
191 | 212 | # print_figure will return None if there's nothing to draw: |
|
192 | 213 | if data is None: |
|
193 | 214 | return |
|
194 | 215 | mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' } |
|
195 | 216 | mime = mimetypes[fmt] |
|
196 | 217 | # flush text streams before sending figures, helps a little with output |
|
197 | 218 | # synchronization in the console (though it's a bandaid, not a real sln) |
|
198 | 219 | sys.stdout.flush(); sys.stderr.flush() |
|
199 | 220 | publish_display_data( |
|
200 | 221 | 'IPython.zmq.pylab.backend_inline.send_figure', |
|
201 | 222 | {mime : data} |
|
202 | 223 | ) |
|
203 | 224 |
General Comments 0
You need to be logged in to leave comments.
Login now