0
# Pyplot Interface
1
2
State-based MATLAB-like interface that maintains a current figure and axes, making it easy to build up plots incrementally. This interface is ideal for interactive work and simple scripts.
3
4
## Core Concepts
5
6
The pyplot interface maintains global state:
7
- Current figure (`gcf()`)
8
- Current axes (`gca()`)
9
- Automatic figure/axes creation when needed
10
11
## Capabilities
12
13
### Figure Management
14
15
Create, manage, and display figures.
16
17
```python { .api }
18
def figure(num=None, figsize=None, dpi=None, facecolor=None,
19
edgecolor=None, frameon=True, FigureClass=Figure,
20
clear=False, **kwargs) -> Figure:
21
"""Create a new figure or activate an existing figure."""
22
23
def gcf() -> Figure:
24
"""Get the current figure."""
25
26
def fignum_exists(num) -> bool:
27
"""Return whether the figure with the given id exists."""
28
29
def show(*args, **kwargs) -> None:
30
"""Display all open figures."""
31
32
def savefig(fname, *, dpi='figure', format=None, metadata=None,
33
bbox_inches=None, pad_inches=0.1, facecolor='auto',
34
edgecolor='auto', backend=None, **kwargs) -> None:
35
"""Save the current figure."""
36
37
def close(fig=None) -> None:
38
"""Close a figure window."""
39
40
def clf() -> None:
41
"""Clear the current figure."""
42
43
def cla() -> None:
44
"""Clear the current axes."""
45
```
46
47
### Basic Plotting
48
49
Fundamental plot types for data visualization.
50
51
```python { .api }
52
def plot(*args, scalex=True, scaley=True, data=None, **kwargs) -> list:
53
"""Plot y versus x as lines and/or markers."""
54
55
def scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None,
56
vmin=None, vmax=None, alpha=None, linewidths=None,
57
edgecolors=None, plotnonfinite=False, **kwargs) -> PathCollection:
58
"""Make a scatter plot of x vs y."""
59
60
def bar(x, height, width=0.8, bottom=None, *, align='center',
61
data=None, **kwargs) -> BarContainer:
62
"""Make a bar plot."""
63
64
def barh(y, width, height=0.8, left=None, *, align='center',
65
data=None, **kwargs) -> BarContainer:
66
"""Make a horizontal bar plot."""
67
68
def hist(x, bins=None, range=None, density=False, weights=None,
69
cumulative=False, bottom=None, histtype='bar', align='mid',
70
orientation='vertical', rwidth=None, log=False, color=None,
71
label=None, stacked=False, **kwargs) -> tuple:
72
"""Compute and plot a histogram."""
73
74
def pie(x, explode=None, labels=None, colors=None, autopct=None,
75
pctdistance=0.6, shadow=False, labeldistance=1.1,
76
startangle=0, radius=1, counterclock=True, wedgeprops=None,
77
textprops=None, center=(0, 0), frame=False, rotatelabels=False,
78
normalize=True, **kwargs) -> tuple:
79
"""Plot a pie chart."""
80
```
81
82
### Statistical Plots
83
84
Specialized plots for statistical data visualization.
85
86
```python { .api }
87
def boxplot(x, notch=None, sym=None, vert=None, whis=None,
88
positions=None, widths=None, patch_artist=None,
89
bootstrap=None, usermedians=None, conf_intervals=None,
90
meanline=None, showmeans=None, showcaps=None,
91
showbox=None, showfliers=None, boxprops=None,
92
labels=None, flierprops=None, medianprops=None,
93
meanprops=None, capprops=None, whiskerprops=None,
94
manage_ticks=True, autorange=False, zorder=None,
95
capwidths=None, **kwargs) -> dict:
96
"""Make a box and whisker plot."""
97
98
def violinplot(dataset, positions=None, vert=True, widths=0.5,
99
showmeans=False, showextrema=True, showmedians=False,
100
quantiles=None, points=100, bw_method=None, **kwargs) -> dict:
101
"""Make a violin plot."""
102
103
def errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None,
104
elinewidth=None, capsize=None, barsabove=False,
105
lolims=False, uplims=False, xlolims=False, xuplims=False,
106
errorevery=1, capthick=None, **kwargs) -> ErrorbarContainer:
107
"""Plot y versus x with error bars."""
108
```
109
110
### 2D Visualization
111
112
Functions for displaying 2D data and images.
113
114
```python { .api }
115
def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None,
116
alpha=None, vmin=None, vmax=None, origin=None, extent=None,
117
filternorm=True, filterrad=4.0, resample=None, url=None,
118
**kwargs) -> AxesImage:
119
"""Display data as an image."""
120
121
def contour(X, Y, Z, levels=None, **kwargs) -> QuadContourSet:
122
"""Draw contour lines."""
123
124
def contourf(X, Y, Z, levels=None, **kwargs) -> QuadContourSet:
125
"""Draw filled contours."""
126
127
def pcolormesh(X, Y, C, **kwargs) -> QuadMesh:
128
"""Create a pseudocolor plot with a non-regular rectangular grid."""
129
130
def quiver(X, Y, U, V, C=None, **kwargs) -> Quiver:
131
"""Plot a 2D field of arrows."""
132
133
def streamplot(x, y, u, v, density=1, linewidth=None, color=None,
134
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
135
minlength=0.1, transform=None, zorder=None,
136
start_points=None, maxlength=4.0, integration_direction='both',
137
**kwargs) -> StreamplotSet:
138
"""Draw streamlines of a vector flow."""
139
```
140
141
### Specialized Plots
142
143
Additional plot types for specific use cases.
144
145
```python { .api }
146
def step(x, y, *args, where='pre', data=None, **kwargs) -> list:
147
"""Make a step plot."""
148
149
def stem(x, y, linefmt=None, markerfmt=None, basefmt=None, bottom=0,
150
label=None, use_line_collection=True, orientation='vertical',
151
**kwargs) -> StemContainer:
152
"""Create a stem plot."""
153
154
def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None,
155
**kwargs) -> PolyCollection:
156
"""Fill the area between two horizontal curves."""
157
158
def fill_betweenx(y, x1, x2=0, where=None, step=None, interpolate=False,
159
**kwargs) -> PolyCollection:
160
"""Fill the area between two vertical curves."""
161
162
def polar(*args, **kwargs) -> list:
163
"""Make a polar plot."""
164
165
def loglog(*args, **kwargs) -> list:
166
"""Make a plot with log scaling on both the x and y axis."""
167
168
def semilogx(*args, **kwargs) -> list:
169
"""Make a plot with log scaling on the x axis."""
170
171
def semilogy(*args, **kwargs) -> list:
172
"""Make a plot with log scaling on the y axis."""
173
```
174
175
### Axes and Subplot Management
176
177
Control plot layout and subplot organization.
178
179
```python { .api }
180
def subplot(nrows, ncols, index, **kwargs) -> Axes:
181
"""Add an axes to the current figure or retrieve an existing axes."""
182
183
def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
184
width_ratios=None, height_ratios=None, subplot_kw=None,
185
gridspec_kw=None, **fig_kw) -> tuple:
186
"""Create a figure and a set of subplots."""
187
188
def subplot_mosaic(mosaic, *, sharex=False, sharey=False, width_ratios=None,
189
height_ratios=None, empty_sentinel='.', subplot_kw=None,
190
gridspec_kw=None, **fig_kw) -> tuple:
191
"""Build a layout of Axes based on ASCII art or nested lists."""
192
193
def gca(**kwargs) -> Axes:
194
"""Get the current Axes."""
195
196
def sca(ax) -> None:
197
"""Set the current Axes."""
198
199
def delaxes(ax=None) -> None:
200
"""Remove an axes from its figure."""
201
```
202
203
### Labeling and Annotation
204
205
Add text, labels, and annotations to plots.
206
207
```python { .api }
208
def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) -> Text:
209
"""Set the label for the x-axis."""
210
211
def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) -> Text:
212
"""Set the label for the y-axis."""
213
214
def title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs) -> Text:
215
"""Set a title for the Axes."""
216
217
def suptitle(t, **kwargs) -> Text:
218
"""Add a centered suptitle to the figure."""
219
220
def text(x, y, s, fontdict=None, **kwargs) -> Text:
221
"""Add text to the Axes."""
222
223
def annotate(text, xy, xytext=None, xycoords='data', textcoords=None,
224
arrowprops=None, annotation_clip=None, **kwargs) -> Annotation:
225
"""Annotate the point xy with text."""
226
227
def legend(*args, **kwargs) -> Legend:
228
"""Place a legend on the Axes."""
229
230
def figtext(x, y, s, fontdict=None, **kwargs) -> Text:
231
"""Add text to figure."""
232
```
233
234
### Axis Control
235
236
Manage axis limits, scaling, and appearance.
237
238
```python { .api }
239
def xlim(left=None, right=None) -> tuple:
240
"""Get or set the x limits of the current axes."""
241
242
def ylim(bottom=None, top=None) -> tuple:
243
"""Get or set the y limits of the current axes."""
244
245
def axis(arg=None, /, *, emit=True, **kwargs):
246
"""Convenience method to get or set some axis properties."""
247
248
def grid(visible=None, which='major', axis='both', **kwargs) -> None:
249
"""Configure the grid lines."""
250
251
def xticks(ticks=None, labels=None, *, minor=False, **kwargs) -> tuple:
252
"""Get or set the current tick locations and labels of the x-axis."""
253
254
def yticks(ticks=None, labels=None, *, minor=False, **kwargs) -> tuple:
255
"""Get or set the current tick locations and labels of the y-axis."""
256
257
def tick_params(axis='both', **kwargs) -> None:
258
"""Change the appearance of ticks, tick labels, and gridlines."""
259
260
def minorticks_on() -> None:
261
"""Display minor ticks on the axes."""
262
263
def minorticks_off() -> None:
264
"""Remove minor ticks from the axes."""
265
```
266
267
### Layout and Formatting
268
269
Control plot layout and visual formatting.
270
271
```python { .api }
272
def tight_layout(*, pad=1.08, h_pad=None, w_pad=None, rect=None) -> None:
273
"""Adjust the padding between and around subplots."""
274
275
def colorbar(mappable=None, cax=None, ax=None, **kwargs) -> Colorbar:
276
"""Add a colorbar to a plot."""
277
278
def clim(vmin=None, vmax=None) -> tuple:
279
"""Set the color limits of the current image."""
280
281
def margins(*margins, x=None, y=None, tight=True) -> tuple:
282
"""Set or retrieve autoscaling margins."""
283
284
def setp(obj, *args, **kwargs):
285
"""Set one or more properties on an Artist, or list allowed values."""
286
287
def getp(obj, property=None):
288
"""Return the value of an Artist's property, or print all of them."""
289
```
290
291
## Usage Examples
292
293
### Simple Line Plot
294
295
```python
296
import matplotlib.pyplot as plt
297
import numpy as np
298
299
x = np.linspace(0, 2*np.pi, 100)
300
y = np.sin(x)
301
302
plt.figure(figsize=(10, 6))
303
plt.plot(x, y, 'b-', linewidth=2, label='sin(x)')
304
plt.xlabel('X values')
305
plt.ylabel('Y values')
306
plt.title('Sine Wave')
307
plt.legend()
308
plt.grid(True)
309
plt.show()
310
```
311
312
### Multiple Subplots
313
314
```python
315
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(12, 10))
316
317
# Plot different things in each subplot
318
ax1.plot(x, np.sin(x))
319
ax1.set_title('Sine')
320
321
ax2.plot(x, np.cos(x))
322
ax2.set_title('Cosine')
323
324
ax3.scatter(x[::10], np.sin(x[::10]))
325
ax3.set_title('Sine Scatter')
326
327
ax4.bar(range(5), [1, 3, 2, 5, 4])
328
ax4.set_title('Bar Chart')
329
330
plt.tight_layout()
331
plt.show()
332
```
333
334
### Statistical Plot
335
336
```python
337
# Generate sample data
338
data = np.random.normal(100, 15, size=(3, 100))
339
340
plt.figure(figsize=(10, 6))
341
plt.boxplot(data, labels=['Group A', 'Group B', 'Group C'])
342
plt.ylabel('Values')
343
plt.title('Box Plot Comparison')
344
plt.grid(True, alpha=0.3)
345
plt.show()
346
```