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