Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 37300c3

Browse files
authored
Merge pull request #23497 from QuLogic/less-gridspec-demo
Avoid gridspec in more examples
2 parents feda7e6 + 0046b38 commit 37300c3

File tree

4 files changed

+63
-73
lines changed

4 files changed

+63
-73
lines changed

examples/images_contours_and_fields/plot_streamplot.py

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,63 +16,58 @@
1616
"""
1717
import numpy as np
1818
import matplotlib.pyplot as plt
19-
import matplotlib.gridspec as gridspec
19+
2020

2121
w = 3
2222
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
2323
U = -1 - X**2 + Y
2424
V = 1 + X - Y**2
2525
speed = np.sqrt(U**2 + V**2)
2626

27-
fig = plt.figure(figsize=(7, 9))
28-
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])
27+
fig, axs = plt.subplots(3, 2, figsize=(7, 9), height_ratios=[1, 1, 2])
28+
axs = axs.flat
2929

3030
# Varying density along a streamline
31-
ax0 = fig.add_subplot(gs[0, 0])
32-
ax0.streamplot(X, Y, U, V, density=[0.5, 1])
33-
ax0.set_title('Varying Density')
31+
axs[0].streamplot(X, Y, U, V, density=[0.5, 1])
32+
axs[0].set_title('Varying Density')
3433

3534
# Varying color along a streamline
36-
ax1 = fig.add_subplot(gs[0, 1])
37-
strm = ax1.streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
35+
strm = axs[1].streamplot(X, Y, U, V, color=U, linewidth=2, cmap='autumn')
3836
fig.colorbar(strm.lines)
39-
ax1.set_title('Varying Color')
37+
axs[1].set_title('Varying Color')
4038

4139
# Varying line width along a streamline
42-
ax2 = fig.add_subplot(gs[1, 0])
4340
lw = 5*speed / speed.max()
44-
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)
45-
ax2.set_title('Varying Line Width')
41+
axs[2].streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)
42+
axs[2].set_title('Varying Line Width')
4643

4744
# Controlling the starting points of the streamlines
4845
seed_points = np.array([[-2, -1, 0, 1, 2, -1], [-2, -1, 0, 1, 2, 2]])
4946

50-
ax3 = fig.add_subplot(gs[1, 1])
51-
strm = ax3.streamplot(X, Y, U, V, color=U, linewidth=2,
52-
cmap='autumn', start_points=seed_points.T)
47+
strm = axs[3].streamplot(X, Y, U, V, color=U, linewidth=2,
48+
cmap='autumn', start_points=seed_points.T)
5349
fig.colorbar(strm.lines)
54-
ax3.set_title('Controlling Starting Points')
50+
axs[3].set_title('Controlling Starting Points')
5551

5652
# Displaying the starting points with blue symbols.
57-
ax3.plot(seed_points[0], seed_points[1], 'bo')
58-
ax3.set(xlim=(-w, w), ylim=(-w, w))
53+
axs[3].plot(seed_points[0], seed_points[1], 'bo')
54+
axs[3].set(xlim=(-w, w), ylim=(-w, w))
5955

6056
# Create a mask
6157
mask = np.zeros(U.shape, dtype=bool)
6258
mask[40:60, 40:60] = True
6359
U[:20, :20] = np.nan
6460
U = np.ma.array(U, mask=mask)
6561

66-
ax4 = fig.add_subplot(gs[2, 0])
67-
ax4.streamplot(X, Y, U, V, color='r')
68-
ax4.set_title('Streamplot with Masking')
62+
axs[4].streamplot(X, Y, U, V, color='r')
63+
axs[4].set_title('Streamplot with Masking')
6964

70-
ax4.imshow(~mask, extent=(-w, w, -w, w), alpha=0.5, cmap='gray', aspect='auto')
71-
ax4.set_aspect('equal')
65+
axs[4].imshow(~mask, extent=(-w, w, -w, w), alpha=0.5, cmap='gray',
66+
aspect='auto')
67+
axs[4].set_aspect('equal')
7268

73-
ax5 = fig.add_subplot(gs[2, 1])
74-
ax5.streamplot(X, Y, U, V, broken_streamlines=False)
75-
ax5.set_title('Streamplot with unbroken streamlines')
69+
axs[5].streamplot(X, Y, U, V, broken_streamlines=False)
70+
axs[5].set_title('Streamplot with unbroken streamlines')
7671

7772
plt.tight_layout()
7873
plt.show()

examples/lines_bars_and_markers/linestyles.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,7 @@ def plot_linestyles(ax, linestyles, title):
6565
color="blue", fontsize=8, ha="right", family="monospace")
6666

6767

68-
ax0, ax1 = (plt.figure(figsize=(10, 8))
69-
.add_gridspec(2, 1, height_ratios=[1, 3])
70-
.subplots())
68+
fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(10, 8), height_ratios=[1, 3])
7169

7270
plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
7371
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')

examples/lines_bars_and_markers/psd_demo.py

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import matplotlib.pyplot as plt
1313
import numpy as np
1414
import matplotlib.mlab as mlab
15-
import matplotlib.gridspec as gridspec
1615

1716
# Fixing random state for reproducibility
1817
np.random.seed(19680801)
@@ -58,39 +57,44 @@
5857
y = y + np.random.randn(*t.shape)
5958

6059
# Plot the raw time series
61-
fig = plt.figure(constrained_layout=True)
62-
gs = gridspec.GridSpec(2, 3, figure=fig)
63-
ax = fig.add_subplot(gs[0, :])
64-
ax.plot(t, y)
65-
ax.set_xlabel('time [s]')
66-
ax.set_ylabel('signal')
60+
fig, axs = plt.subplot_mosaic([
61+
['signal', 'signal', 'signal'],
62+
['zero padding', 'block size', 'overlap'],
63+
], layout='constrained')
64+
65+
axs['signal'].plot(t, y)
66+
axs['signal'].set_xlabel('time [s]')
67+
axs['signal'].set_ylabel('signal')
6768

6869
# Plot the PSD with different amounts of zero padding. This uses the entire
6970
# time series at once
70-
ax2 = fig.add_subplot(gs[1, 0])
71-
ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
72-
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs)
73-
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs)
74-
ax2.set_title('zero padding')
71+
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
72+
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs)
73+
axs['zero padding'].psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs)
7574

7675
# Plot the PSD with different block sizes, Zero pad to the length of the
7776
# original data sequence.
78-
ax3 = fig.add_subplot(gs[1, 1], sharex=ax2, sharey=ax2)
79-
ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
80-
ax3.psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs)
81-
ax3.psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs)
82-
ax3.set_ylabel('')
83-
ax3.set_title('block size')
77+
axs['block size'].psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
78+
axs['block size'].psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs)
79+
axs['block size'].psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs)
80+
axs['block size'].set_ylabel('')
8481

8582
# Plot the PSD with different amounts of overlap between blocks
86-
ax4 = fig.add_subplot(gs[1, 2], sharex=ax2, sharey=ax2)
87-
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs)
88-
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
89-
noverlap=int(0.05 * len(t) / 2.), Fs=fs)
90-
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
91-
noverlap=int(0.2 * len(t) / 2.), Fs=fs)
92-
ax4.set_ylabel('')
93-
ax4.set_title('overlap')
83+
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs)
84+
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t),
85+
noverlap=int(0.025 * len(t)), Fs=fs)
86+
axs['overlap'].psd(y, NFFT=len(t) // 2, pad_to=len(t),
87+
noverlap=int(0.1 * len(t)), Fs=fs)
88+
axs['overlap'].set_ylabel('')
89+
axs['overlap'].set_title('overlap')
90+
91+
for title, ax in axs.items():
92+
if title == 'signal':
93+
continue
94+
95+
ax.set_title(title)
96+
ax.sharex(axs['zero padding'])
97+
ax.sharey(axs['zero padding'])
9498

9599
plt.show()
96100

examples/text_labels_and_annotations/demo_text_rotation_mode.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,14 @@
2020
"""
2121

2222
import matplotlib.pyplot as plt
23-
import numpy as np
2423

2524

26-
def test_rotation_mode(fig, mode, subplot_location):
25+
def test_rotation_mode(fig, mode):
2726
ha_list = ["left", "center", "right"]
2827
va_list = ["top", "center", "baseline", "bottom"]
29-
axs = np.empty((len(va_list), len(ha_list)), object)
30-
gs = subplot_location.subgridspec(*axs.shape, hspace=0, wspace=0)
31-
axs[0, 0] = fig.add_subplot(gs[0, 0])
32-
for i in range(len(va_list)):
33-
for j in range(len(ha_list)):
34-
if (i, j) == (0, 0):
35-
continue # Already set.
36-
axs[i, j] = fig.add_subplot(
37-
gs[i, j], sharex=axs[0, 0], sharey=axs[0, 0])
38-
for ax in axs.flat:
39-
ax.set(aspect=1)
28+
axs = fig.subplots(len(va_list), len(ha_list), sharex=True, sharey=True,
29+
subplot_kw=dict(aspect=1),
30+
gridspec_kw=dict(hspace=0, wspace=0))
4031

4132
# labels and title
4233
for ha, ax in zip(ha_list, axs[-1, :]):
@@ -50,6 +41,8 @@ def test_rotation_mode(fig, mode, subplot_location):
5041
{"bbox": dict(boxstyle="square,pad=0.", ec="none", fc="C1", alpha=0.3)}
5142
)
5243

44+
texts = {}
45+
5346
# use a different text alignment in each axes
5447
for i, va in enumerate(va_list):
5548
for j, ha in enumerate(ha_list):
@@ -64,22 +57,22 @@ def test_rotation_mode(fig, mode, subplot_location):
6457
size="x-large", rotation=40,
6558
horizontalalignment=ha, verticalalignment=va,
6659
rotation_mode=mode, **kw)
60+
texts[ax] = tx
6761

6862
if mode == "default":
6963
# highlight bbox
7064
fig.canvas.draw()
71-
for ax in axs.flat:
72-
text, = ax.texts
65+
for ax, text in texts.items():
7366
bb = text.get_window_extent().transformed(ax.transData.inverted())
7467
rect = plt.Rectangle((bb.x0, bb.y0), bb.width, bb.height,
7568
facecolor="C1", alpha=0.3, zorder=2)
7669
ax.add_patch(rect)
7770

7871

7972
fig = plt.figure(figsize=(8, 5))
80-
gs = fig.add_gridspec(1, 2)
81-
test_rotation_mode(fig, "default", gs[0])
82-
test_rotation_mode(fig, "anchor", gs[1])
73+
subfigs = fig.subfigures(1, 2)
74+
test_rotation_mode(subfigs[0], "default")
75+
test_rotation_mode(subfigs[1], "anchor")
8376
plt.show()
8477

8578

0 commit comments

Comments
 (0)