调整子图以为色条留出空间

2024-04-26 07:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图绘制一些数据,发现约束布局在维护子地块之间的边距和空间方面非常有用。但是,当我添加颜色条时,它会减少所有子图的宽度,并在上面的子图中创建额外的空白。当在报告中显示这样的绘图时,由于colorbar占用了额外的空间而浪费了大量的空间,这就产生了一个问题。 我想知道如何避免这种情况,在添加颜色栏时只调整图像打印大小,而不考虑上面的子图,也不创建额外的空白。我面临的问题的一个示例代码是:

fig, ax = plt.subplots(4,2, constrained_layout=True)
ax[0,0].plot(range(10))
ax[0,1].plot(range(10))
ax[1,0].plot(range(10))
ax[1,1].plot(range(10))
ax[2,0].pcolor(np.random.rand(2,2))
ax[2,1].pcolor(np.random.rand(2,2))
ax[3,0].pcolor(np.random.rand(2,2))
im = ax[3,1].pcolor(np.random.rand(2,2))
bar = fig.colorbar(im,ax=[[ax[2,0],ax[2,1]],[ax[3,0],ax[3,1]]])

如果我能用contracted_layout=True完成这项工作会更好


Tags: trueplot颜色npfig空间rangerandom
1条回答
网友
1楼 · 发布于 2024-04-26 07:27:35

我在调整颜色栏方面没有太多经验,但是添加一个新的轴并将颜色栏放置在中心的想法呢?我手动设置放置值。我想把颜色条放在下面两个图形中,使宽度相同,但我做不到

import matplotlib.pyplot as plt

fig, ax = plt.subplots(4,2, constrained_layout=True)
ax[0,0].plot(range(10))
ax[0,1].plot(range(10))
ax[1,0].plot(range(10))
ax[1,1].plot(range(10))
ax[2,0].pcolor(np.random.rand(2,2))
ax[2,1].pcolor(np.random.rand(2,2))
ax[3,0].pcolor(np.random.rand(2,2))
im = ax[3,1].pcolor(np.random.rand(2,2))

cax = fig.add_axes([0.48, 0.11, 0.05, 0.36])
bar = fig.colorbar(im,cax=cax,ax=[[ax[2,0],ax[2,1]],[ax[3,0],ax[3,1]]])

fig.subplots_adjust(wspace=0.7, hspace=0.5)

plt.show()

enter image description here

相关问题 更多 >