我有一个 2*4 子图,其中一半的 ylabel 和 yticklabels 被禁用。不幸的是,tight_layout() 不会删除与 ylabel 和 yticklabels 未禁用时出现的区域相对应的额外空白。ylabel 和 yticklabels 被删除,因为我想要 4 对比较子图。情节看起来是这样的。
我正在寻找一种有效的方法来删除多余的空白。事实上,我希望每对地块都彼此相邻,根本没有空间。这是一个工作示例。
import matplotlib.pyplot as plt
fig, ((ax0, ax1, ax2, ax3), (ax4, ax5, ax6, ax7)) = plt.subplots(2, 4, figsize=(8, 4))
axs = [ax0, ax1, ax2, ax3, ax4, ax5, ax6, ax7]
for i in range(4):
axs[2*i].set_ylabel('parameter '+str(i))
axs[2*i+1].set_yticklabels([])
plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)
代码应该产生上面的图。任何提示将不胜感激。非常感谢!
您可以通过拥有两个子网格并强制轴之间的距离为零来实现这一点(我遵循了本教程)。该wspace参数的描述见此处。
import matplotlib.pyplot as plt
fig = plt.figure(constrained_layout=False) # you must disable automatic spacing
gs = fig.add_gridspec(1, 2, figure=fig)
gs0 = gs[0].subgridspec(2, 2, wspace=0.0)
gs1 = gs[1].subgridspec(2, 2, wspace=0.0)
axs = [[],[]]
for i in range(2):
for j in range(2):
axs[0].append(fig.add_subplot(gs0[i, j]))
axs[1].append(fig.add_subplot(gs1[i, j]))
axs = [*axs[0],*axs[1]]
for i in range(4):
axs[2*i].set_ylabel('parameter ' + str(i))
axs[2*i+1].set_yticklabels([])
Run Code Online (Sandbox Code Playgroud)
由于自动间距被禁用,您可能必须使用轴和图形属性来调整轴、标签等的位置。
部分(距离不会为空,但其他用户可能会感兴趣),更优雅的解决方案是使用constrained_layout在创建图形时使用。更多信息请参见matplotlib 的文档。
import matplotlib.pyplot as plt
fig, axs = plt.subplots(
2, 4,
figsize=(8, 4),
constrained_layout=True,
)
axs = axs.reshape([8])
for i in range(4):
axs[2*i].set_ylabel('parameter '+str(i))
axs[2*i+1].set_yticklabels([])
# plt.tight_layout() # not necessary
plt.show()
Run Code Online (Sandbox Code Playgroud)