在子图中更改绘图大小
我创建了一个包含4个子图的图形(2行2列),其中3个是用imshow
显示的,另一个是用errorbar
显示的。每个imshow
的图旁边都有一个颜色条。我想调整我的第三个图的大小,让它的区域正好在上面的图下面(不带颜色条)。
比如说(这是我现在的样子):
我该如何调整第三个图的大小呢?
谢谢!
1 个回答
5
要调整坐标轴的大小,你需要使用 set_position() 这个方法。这同样适用于子图的坐标轴。要获取当前坐标轴的位置或大小,可以使用 get_position() 方法,它会返回一个 Bbox 实例。对我来说,直接处理位置,比如 [左边, 底部, 右边, 顶部] 的限制,更容易理解。要从 Bbox 中获取这些信息,可以使用 bounds 属性。
这里我把这些方法应用到一个类似你上面例子的东西上:
import matplotlib.pyplot as plt
import numpy as np
x,y = np.random.rand(2,10)
img = np.random.rand(10,10)
fig = plt.figure()
ax1 = fig.add_subplot(221)
im = ax1.imshow(img,extent=[0,1,0,1])
plt.colorbar(im)
ax2 = fig.add_subplot(222)
im = ax2.imshow(img,extent=[0,1,0,1])
plt.colorbar(im)
ax3 = fig.add_subplot(223)
ax3.plot(x,y)
ax3.axis([0,1,0,1])
ax4 = fig.add_subplot(224)
im = ax4.imshow(img,extent=[0,1,0,1])
plt.colorbar(im)
pos4 = ax4.get_position().bounds
pos1 = ax1.get_position().bounds
# set the x limits (left and right) to first axes limits
# set the y limits (bottom and top) to the last axes limits
newpos = [pos1[0],pos4[1],pos1[2],pos4[3]]
ax3.set_position(newpos)
plt.show()
你可能会觉得这两个图看起来不完全一样(在我的渲染中,左边或最小 x 位置有点不对),所以可以随意调整位置,直到达到你想要的效果。