更改子图中的绘图大小

Eag*_*gle 1 python matplotlib

我创建了一个包含 4 个子图 (2 x 2) 的图形,其中 3 个是 类型,imshow另一个是errorbar. 每个imshow图的右侧还有一个颜色条。我想调整我的第三个图的大小,该图的面积将正好位于其上方的图的下方(没有颜色条)

例如(这就是我现在拥有的):

例子

我如何调整第三个图的大小?

问候

Yan*_*ann 5

要调整坐标区实例的尺寸,您需要使用set_position()方法。这也适用于 subplotAxes。要获取轴的当前位置/尺寸,请使用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()
Run Code Online (Sandbox Code Playgroud)

您可能会觉得这两个图看起来不太一样(在我的渲染中,左侧或 xmin 位置不太正确),因此请随意调整位置,直到获得所需的效果。