python - 如何使用 pyplot/gridspec 增加单个子图的大小?

标签 python matplotlib

我正在尝试在 6x4 网格中绘制 23 个图形,其中一个图形的宽度是其他图形宽度的两倍。我正在使用 gridspec,我当前的代码是:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

x = np.arange(0, 7, 0.01)

fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=6, ncols=4)

for n in range(22):
    ax = fig.add_subplot(gs[n])
    ax.plot(x, np.sin(0.2*n*x))

corrax = fig.add_subplot(gs[22])
fig.tight_layout()
plt.show()

这会产生以下结果:

Figure grid

我想增加底行最右边图的宽度,以便它占据该行的剩余空间。有办法实现吗?

最佳答案

您可以使用切片从网格规范中选择多个位置,例如gs[22:24]

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

x = np.arange(0, 7, 0.01)

fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=6, ncols=4)

for n in range(22):
    ax = fig.add_subplot(gs[n])
    ax.plot(x, np.sin(0.2*n*x))

corrax = fig.add_subplot(gs[22:24])
corrax.plot(x,np.sin(0.2*22*x), color="crimson", lw=3)
fig.tight_layout()
plt.show()

enter image description here

您还可以对 gridspec 进行二维切片。例如。要创建 3x3 网格并使右下角的图跨越两列和两行,您可以像 gs[1:,1:] 那样进行切片。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec

x = np.arange(0, 7, 0.01)

fig = plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(nrows=3, ncols=3)

for n in range(3):
    ax = fig.add_subplot(gs[0,n])
    ax.plot(x, np.sin(0.2*n*x))
    if n !=0:
        ax = fig.add_subplot(gs[n,0])
        ax.plot(x, np.sin(0.2*n*x))

corrax = fig.add_subplot(gs[1:,1:])
corrax.plot(x,np.sin(0.2*22*x), color="crimson", lw=3)
fig.tight_layout()
plt.show()

enter image description here

关于python - 如何使用 pyplot/gridspec 增加单个子图的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47435055/

相关文章:

python - 使用 FFT 数组的 matplotlib pcolormesh 中的错误行为?

python - 如何在 Python 上使用 Selenium 从网站上抓取全名?

python - RNN 的 tf.clip_by_value 和 tf.clip_by_global_norm 之间的区别以及如何确定要剪辑的最大值?

python - 查找图中从 A 到 N 的所有路径

python - django lambda 和 django-activity-stream

python - 使用 matplotlib 从 CSV 文件中绘制数据

python - 步幅为 2 和最大池化层的步幅卷积的维数

matplotlib - 无法从 'animation' 导入名称 'matplotlib'

python - Matplotlib 不在 X 轴上绘制水平线

python - 使用不同颜色的切片图 - 手动重新着色条形