我正在尝试在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()
这会产生以下结果:
我想增加底行中最右边的绘图的宽度,以便占用该行中的剩余空间。有没有办法实现这个目标?
答案 0 :(得分:4)
您可以使用切片从gridspec中选择多个位置,例如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()
您还可以二维切片格子规格。例如。要创建一个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()
答案 1 :(得分:0)