##// END OF EJS Templates
Merge pull request #892 from minrk/show...
Fernando Perez -
r5123:d2b3a0c6 merge
parent child Browse files
Show More
@@ -1,116 +1,163
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.lib.pylabtools import print_figure, select_figure_format
19 from IPython.lib.pylabtools import print_figure, select_figure_format
20 from IPython.utils.traitlets import Dict, Instance, CaselessStrEnum
20 from IPython.utils.traitlets import Dict, Instance, CaselessStrEnum, CBool
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Configurable for inline backend options
22 # Configurable for inline backend options
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class InlineBackendConfig(SingletonConfigurable):
25 class InlineBackendConfig(SingletonConfigurable):
26 """An object to store configuration of the inline backend."""
26 """An object to store configuration of the inline backend."""
27
27
28 # The typical default figure size is too large for inline use,
28 # The typical default figure size is too large for inline use,
29 # so we shrink the figure size to 6x4, and tweak fonts to
29 # so we shrink the figure size to 6x4, and tweak fonts to
30 # make that fit. This is configurable via Global.pylab_inline_rc,
30 # make that fit. This is configurable via Global.pylab_inline_rc,
31 # or rather it will be once the zmq kernel is hooked up to
31 # or rather it will be once the zmq kernel is hooked up to
32 # the config system.
32 # the config system.
33 rc = Dict({'figure.figsize': (6.0,4.0),
33 rc = Dict({'figure.figsize': (6.0,4.0),
34 # 12pt labels get cutoff on 6x4 logplots, so use 10pt.
34 # 12pt labels get cutoff on 6x4 logplots, so use 10pt.
35 'font.size': 10,
35 'font.size': 10,
36 # 10pt still needs a little more room on the xlabel:
36 # 10pt still needs a little more room on the xlabel:
37 'figure.subplot.bottom' : .125
37 'figure.subplot.bottom' : .125
38 }, config=True,
38 }, config=True,
39 help="""Subset of matplotlib rcParams that should be different for the
39 help="""Subset of matplotlib rcParams that should be different for the
40 inline backend."""
40 inline backend."""
41 )
41 )
42 figure_format = CaselessStrEnum(['svg', 'png'], default_value='png', config=True,
42 figure_format = CaselessStrEnum(['svg', 'png'], default_value='png', config=True,
43 help="The image format for figures with the inline backend.")
43 help="The image format for figures with the inline backend.")
44
44
45 def _figure_format_changed(self, name, old, new):
45 def _figure_format_changed(self, name, old, new):
46 if self.shell is None:
46 if self.shell is None:
47 return
47 return
48 else:
48 else:
49 select_figure_format(self.shell, new)
49 select_figure_format(self.shell, new)
50
50
51 close_figures = CBool(True, config=True,
52 help="""Close all figures at the end of each cell.
53
54 When True, ensures that each cell starts with no active figures, but it
55 also means that one must keep track of references in order to edit or
56 redraw figures in subsequent cells. This mode is ideal for the notebook,
57 where residual plots from other cells might be surprising.
58
59 When False, one must call figure() to create new figures. This means
60 that gcf() and getfigs() can reference figures created in other cells,
61 and the active figure can continue to be edited with pylab/pyplot
62 methods that reference the current active figure. This mode facilitates
63 iterative editing of figures, and behaves most consistently with
64 other matplotlib backends, but figure barriers between cells must
65 be explicit.
66 """)
67
51 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
68 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
52
69
53
70
54 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
55 # Functions
72 # Functions
56 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
57
74
58 def show(close=True):
75 def show(close=None):
59 """Show all figures as SVG payloads sent to the IPython clients.
76 """Show all figures as SVG/PNG payloads sent to the IPython clients.
60
77
61 Parameters
78 Parameters
62 ----------
79 ----------
63 close : bool, optional
80 close : bool, optional
64 If true, a ``plt.close('all')`` call is automatically issued after
81 If true, a ``plt.close('all')`` call is automatically issued after
65 sending all the SVG figures. If this is set, the figures will entirely
82 sending all the figures. If this is set, the figures will entirely
66 removed from the internal list of figures.
83 removed from the internal list of figures.
67 """
84 """
85 if close is None:
86 close = InlineBackendConfig.instance().close_figures
68 for figure_manager in Gcf.get_all_fig_managers():
87 for figure_manager in Gcf.get_all_fig_managers():
69 send_figure(figure_manager.canvas.figure)
88 send_figure(figure_manager.canvas.figure)
70 if close:
89 if close:
71 matplotlib.pyplot.close('all')
90 matplotlib.pyplot.close('all')
91 show._to_draw = []
92
72
93
73
94
74 # This flag will be reset by draw_if_interactive when called
95 # This flag will be reset by draw_if_interactive when called
75 show._draw_called = False
96 show._draw_called = False
97 # list of figures to draw when flush_figures is called
98 show._to_draw = []
76
99
77
100
78 def draw_if_interactive():
101 def draw_if_interactive():
79 """
102 """
80 Is called after every pylab drawing command
103 Is called after every pylab drawing command
81 """
104 """
82 # We simply flag we were called and otherwise do nothing. At the end of
105 # signal that the current active figure should be sent at the end of execution.
83 # the code execution, a separate call to show_close() will act upon this.
106 # Also sets the _draw_called flag, signaling that there will be something to send.
107 # At the end of the code execution, a separate call to flush_figures()
108 # will act upon these values
109
110 fig = Gcf.get_active().canvas.figure
111
112 # ensure current figure will be drawn, and each subsequent call
113 # of draw_if_interactive() moves the active figure to ensure it is
114 # drawn last
115 try:
116 show._to_draw.remove(fig)
117 except ValueError:
118 # ensure it only appears in the draw list once
119 pass
120 show._to_draw.append(fig)
84 show._draw_called = True
121 show._draw_called = True
85
122
86
87 def flush_figures():
123 def flush_figures():
88 """Call show, close all open figures, sending all figure images.
124 """Send all figures that changed
89
125
90 This is meant to be called automatically and will call show() if, during
126 This is meant to be called automatically and will call show() if, during
91 prior code execution, there had been any calls to draw_if_interactive.
127 prior code execution, there had been any calls to draw_if_interactive.
92 """
128 """
93 if show._draw_called:
129 if not show._draw_called:
94 show()
130 return
131
132 if InlineBackendConfig.instance().close_figures:
133 # ignore the tracking, just draw and close all figures
134 return show(True)
135
136 # exclude any figures that were closed:
137 active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
138 for fig in [ fig for fig in show._to_draw if fig in active ]:
139 send_figure(fig)
140 # clear flags for next round
141 show._to_draw = []
95 show._draw_called = False
142 show._draw_called = False
96
143
97
144
98 def send_figure(fig):
145 def send_figure(fig):
99 """Draw the current figure and send it as a PNG payload.
146 """Draw the current figure and send it as a PNG payload.
100 """
147 """
101 # For an empty figure, don't even bother calling figure_to_svg, to avoid
148 # For an empty figure, don't even bother calling figure_to_svg, to avoid
102 # big blank spaces in the qt console
149 # big blank spaces in the qt console
103 if not fig.axes:
150 if not fig.axes:
104 return
151 return
105 fmt = InlineBackendConfig.instance().figure_format
152 fmt = InlineBackendConfig.instance().figure_format
106 data = print_figure(fig, fmt)
153 data = print_figure(fig, fmt)
107 mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
154 mimetypes = { 'png' : 'image/png', 'svg' : 'image/svg+xml' }
108 mime = mimetypes[fmt]
155 mime = mimetypes[fmt]
109 # flush text streams before sending figures, helps a little with output
156 # flush text streams before sending figures, helps a little with output
110 # synchronization in the console (though it's a bandaid, not a real sln)
157 # synchronization in the console (though it's a bandaid, not a real sln)
111 sys.stdout.flush(); sys.stderr.flush()
158 sys.stdout.flush(); sys.stderr.flush()
112 publish_display_data(
159 publish_display_data(
113 'IPython.zmq.pylab.backend_inline.send_figure',
160 'IPython.zmq.pylab.backend_inline.send_figure',
114 {mime : data}
161 {mime : data}
115 )
162 )
116
163
General Comments 0
You need to be logged in to leave comments. Login now