0
# Matplotlib Integration
1
2
Specialized support for matplotlib inline plotting, display hooks for rich output, and integration with Jupyter's display system. Enables seamless matplotlib visualization within Jupyter notebooks and other frontends.
3
4
## Capabilities
5
6
### Inline Backend Functions
7
8
Core functions for matplotlib inline display in Jupyter environments.
9
10
```python { .api }
11
def show(close=None):
12
"""
13
Display matplotlib figures inline.
14
15
Shows all active matplotlib figures in the Jupyter frontend
16
and optionally closes them after display.
17
18
Parameters:
19
- close (bool, optional): Whether to close figures after showing
20
If None, uses configuration default
21
"""
22
23
def draw_if_interactive():
24
"""
25
Draw figures if matplotlib is in interactive mode.
26
27
Triggers drawing of matplotlib figures when in interactive mode,
28
ensuring plots are updated in Jupyter frontends.
29
"""
30
31
def flush_figures():
32
"""
33
Flush all pending matplotlib figures.
34
35
Forces display of all matplotlib figures that are ready to be shown,
36
ensuring they appear in the Jupyter frontend.
37
"""
38
```
39
40
### Backend Configuration
41
42
Functions for configuring matplotlib's inline backend behavior.
43
44
```python { .api }
45
def configure_inline_support(shell, backend):
46
"""
47
Configure matplotlib inline backend for IPython shell.
48
49
Sets up matplotlib integration with the IPython shell, enabling
50
inline display of plots and configuring display hooks.
51
52
Parameters:
53
- shell: IPython shell instance
54
- backend: Matplotlib backend configuration
55
"""
56
```
57
58
### Inline Backend Configuration Classes
59
60
Classes for managing matplotlib inline backend settings and behavior.
61
62
```python { .api }
63
class InlineBackendConfig:
64
"""
65
Configuration class for matplotlib inline backend.
66
67
Manages settings for how matplotlib figures are displayed
68
inline in Jupyter environments.
69
"""
70
71
# Configuration attributes
72
figure_formats: set # Set of figure formats to use
73
print_figure_kwargs: dict # Keyword arguments for figure printing
74
close_figures: bool # Whether to close figures after display
75
shell: object # Reference to IPython shell
76
77
class InlineBackend:
78
"""
79
Main inline backend class for matplotlib integration.
80
81
Handles the display and formatting of matplotlib figures
82
within Jupyter notebook environments.
83
"""
84
85
def show(self, close=None):
86
"""
87
Show matplotlib figures inline.
88
89
Parameters:
90
- close (bool, optional): Whether to close after showing
91
"""
92
93
def draw_if_interactive(self):
94
"""Draw figures if in interactive mode."""
95
96
def flush_figures(self):
97
"""Flush all pending figures."""
98
99
# Backend configuration
100
config: InlineBackendConfig # Backend configuration object
101
```
102
103
## Usage Examples
104
105
### Basic Inline Plotting
106
107
```python
108
from ipykernel.pylab.backend_inline import show, flush_figures
109
import matplotlib.pyplot as plt
110
import numpy as np
111
112
# Create a simple plot
113
x = np.linspace(0, 10, 100)
114
y = np.sin(x)
115
116
plt.figure(figsize=(10, 6))
117
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
118
plt.xlabel('X values')
119
plt.ylabel('Y values')
120
plt.title('Sine Wave Plot')
121
plt.legend()
122
plt.grid(True)
123
124
# Display the plot inline
125
show()
126
```
127
128
### Multiple Figure Display
129
130
```python
131
from ipykernel.pylab.backend_inline import show, flush_figures
132
import matplotlib.pyplot as plt
133
import numpy as np
134
135
# Create multiple figures
136
x = np.linspace(0, 10, 100)
137
138
# Figure 1: Sine wave
139
plt.figure(1, figsize=(8, 4))
140
plt.plot(x, np.sin(x), 'b-', label='sin(x)')
141
plt.title('Sine Wave')
142
plt.legend()
143
144
# Figure 2: Cosine wave
145
plt.figure(2, figsize=(8, 4))
146
plt.plot(x, np.cos(x), 'r-', label='cos(x)')
147
plt.title('Cosine Wave')
148
plt.legend()
149
150
# Figure 3: Both waves
151
plt.figure(3, figsize=(10, 6))
152
plt.plot(x, np.sin(x), 'b-', label='sin(x)')
153
plt.plot(x, np.cos(x), 'r-', label='cos(x)')
154
plt.title('Sine and Cosine Waves')
155
plt.legend()
156
157
# Display all figures
158
flush_figures()
159
```
160
161
### Interactive Plotting with Updates
162
163
```python
164
from ipykernel.pylab.backend_inline import show, draw_if_interactive
165
import matplotlib.pyplot as plt
166
import numpy as np
167
import time
168
169
# Enable interactive mode
170
plt.ion()
171
172
# Create figure
173
fig, ax = plt.subplots(figsize=(10, 6))
174
x = np.linspace(0, 10, 100)
175
176
# Initial plot
177
line, = ax.plot(x, np.sin(x), 'b-', linewidth=2)
178
ax.set_xlabel('X values')
179
ax.set_ylabel('Y values')
180
ax.set_title('Animated Sine Wave')
181
ax.grid(True)
182
183
# Show initial plot
184
show()
185
186
# Animate the plot
187
for phase in np.linspace(0, 4*np.pi, 20):
188
# Update data
189
y = np.sin(x + phase)
190
line.set_ydata(y)
191
192
# Trigger redraw
193
draw_if_interactive()
194
195
# Small delay for animation effect
196
time.sleep(0.1)
197
198
plt.ioff() # Turn off interactive mode
199
```
200
201
### Custom Figure Configuration
202
203
```python
204
from ipykernel.pylab.backend_inline import configure_inline_support, show
205
from ipykernel.pylab.config import InlineBackend, InlineBackendConfig
206
import matplotlib.pyplot as plt
207
import numpy as np
208
209
# Configure matplotlib for high-quality inline display
210
config = InlineBackendConfig()
211
config.figure_formats = {'png', 'svg'} # Use both PNG and SVG
212
config.print_figure_kwargs = {
213
'bbox_inches': 'tight',
214
'dpi': 150,
215
'facecolor': 'white'
216
}
217
config.close_figures = True # Close figures after display
218
219
# Create custom backend with configuration
220
backend = InlineBackend()
221
backend.config = config
222
223
# Create high-quality plot
224
plt.figure(figsize=(12, 8))
225
x = np.linspace(0, 20, 1000)
226
y1 = np.sin(x) * np.exp(-x/10)
227
y2 = np.cos(x) * np.exp(-x/10)
228
229
plt.plot(x, y1, 'b-', linewidth=2, label='Damped Sine', alpha=0.8)
230
plt.plot(x, y2, 'r-', linewidth=2, label='Damped Cosine', alpha=0.8)
231
plt.fill_between(x, y1, alpha=0.3, color='blue')
232
plt.fill_between(x, y2, alpha=0.3, color='red')
233
234
plt.xlabel('Time', fontsize=14)
235
plt.ylabel('Amplitude', fontsize=14)
236
plt.title('Damped Oscillations', fontsize=16, fontweight='bold')
237
plt.legend(fontsize=12)
238
plt.grid(True, alpha=0.3)
239
240
# Display with custom configuration
241
backend.show()
242
```
243
244
### Subplot Management
245
246
```python
247
from ipykernel.pylab.backend_inline import show
248
import matplotlib.pyplot as plt
249
import numpy as np
250
251
# Create subplot figure
252
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
253
fig.suptitle('Multiple Subplot Example', fontsize=16, fontweight='bold')
254
255
x = np.linspace(0, 10, 100)
256
257
# Subplot 1: Linear function
258
axes[0, 0].plot(x, x, 'b-', linewidth=2)
259
axes[0, 0].set_title('Linear: y = x')
260
axes[0, 0].grid(True)
261
262
# Subplot 2: Quadratic function
263
axes[0, 1].plot(x, x**2, 'r-', linewidth=2)
264
axes[0, 1].set_title('Quadratic: y = x²')
265
axes[0, 1].grid(True)
266
267
# Subplot 3: Exponential function
268
axes[1, 0].plot(x, np.exp(x/5), 'g-', linewidth=2)
269
axes[1, 0].set_title('Exponential: y = e^(x/5)')
270
axes[1, 0].grid(True)
271
272
# Subplot 4: Logarithmic function
273
x_log = np.linspace(0.1, 10, 100)
274
axes[1, 1].plot(x_log, np.log(x_log), 'm-', linewidth=2)
275
axes[1, 1].set_title('Logarithmic: y = ln(x)')
276
axes[1, 1].grid(True)
277
278
# Adjust layout and display
279
plt.tight_layout()
280
show()
281
```
282
283
### Integration with IPython Display System
284
285
```python
286
from ipykernel.pylab.backend_inline import show
287
from IPython.display import display, Image, SVG
288
import matplotlib.pyplot as plt
289
import numpy as np
290
import io
291
import base64
292
293
def create_plot_data():
294
"""Create sample plot data."""
295
x = np.linspace(0, 2*np.pi, 100)
296
y1 = np.sin(x)
297
y2 = np.cos(x)
298
return x, y1, y2
299
300
def plot_to_base64(fig, format='png', dpi=100):
301
"""Convert matplotlib figure to base64 string."""
302
buffer = io.BytesIO()
303
fig.savefig(buffer, format=format, dpi=dpi, bbox_inches='tight')
304
buffer.seek(0)
305
image_data = buffer.getvalue()
306
buffer.close()
307
308
return base64.b64encode(image_data).decode()
309
310
# Create plot
311
x, y1, y2 = create_plot_data()
312
313
fig, ax = plt.subplots(figsize=(10, 6))
314
ax.plot(x, y1, 'b-', linewidth=2, label='sin(x)')
315
ax.plot(x, y2, 'r--', linewidth=2, label='cos(x)')
316
ax.set_xlabel('Angle (radians)')
317
ax.set_ylabel('Value')
318
ax.set_title('Trigonometric Functions')
319
ax.legend()
320
ax.grid(True, alpha=0.3)
321
322
# Display using different methods
323
print("Method 1: Standard inline display")
324
show()
325
326
print("Method 2: Manual base64 encoding")
327
b64_data = plot_to_base64(fig)
328
display(Image(data=base64.b64decode(b64_data)))
329
330
plt.close(fig) # Clean up
331
```
332
333
### Error Handling and Cleanup
334
335
```python
336
from ipykernel.pylab.backend_inline import show, flush_figures
337
import matplotlib.pyplot as plt
338
import numpy as np
339
340
def safe_plot_display():
341
"""Safely create and display plots with error handling."""
342
try:
343
# Create plot
344
x = np.linspace(0, 10, 100)
345
y = np.sin(x) / x # This might cause division by zero
346
347
plt.figure(figsize=(8, 6))
348
plt.plot(x, y, 'b-', linewidth=2)
349
plt.title('sinc(x) = sin(x)/x')
350
plt.xlabel('x')
351
plt.ylabel('sinc(x)')
352
plt.grid(True)
353
354
# Display plot
355
show(close=True) # Close after showing
356
357
print("Plot displayed successfully")
358
359
except Exception as e:
360
print(f"Error creating plot: {e}")
361
362
# Clean up any partial figures
363
plt.close('all')
364
365
finally:
366
# Ensure all figures are flushed
367
flush_figures()
368
369
# Run safe plotting
370
safe_plot_display()
371
372
# Verify no figures remain open
373
print(f"Open figures: {plt.get_fignums()}")
374
```