在 matlab 中,获取和设置图形上现有轴的位置非常简单:
pos = get(gca(), 'position')
set(gca(), 'position', pos)
如何在 Matplotlib 中执行此操作?
我需要这个有两个相关原因:
这些是我试图解决的具体问题:
我有一列子图,其中有些有颜色条,有些没有,而且它们的宽度不同,即 X 轴不对齐。颜色条从轴上窃取了空间。这种情况在 matlab 中也会发生,我将使用上述技巧,通过将带有颜色条的轴的宽度复制到没有颜色条的轴,使所有轴的宽度相等。
通过缩小轴来添加各个子图之间的空间。 adjustment_subplots() 函数对所有子图进行相同的调整。
设置轴位置与 Matplotlib 中类似。您可以使用 axes 的 get_position 和 set_position 方法。
import matplotlib.pyplot as plt
ax = plt.subplot(111)
pos1 = ax.get_position() # get the original position
pos2 = [pos1.x0 + 0.3, pos1.y0 + 0.3, pos1.width / 2.0, pos1.height / 2.0]
ax.set_position(pos2) # set a new position
如果您还没有看过,您可能还想看看 GridSpec。
get_position()
或_position
获取ax
的位置; set_position()
在图窗上的新位置设置 现有 ax
。
但是,在许多情况下,最好在图上的特定位置添加 new 轴,在这种情况下,
add_axes()
可能会很有用。它允许以非常灵活的方式向现有图形添加轴(和绘图)。例如,在以下代码中,线图(在 ax2
上绘制)叠加在散点图(在 ax1
上绘制)
import matplotlib.pyplot as plt
x = range(10)
fig, ax1 = plt.subplots()
ax1.scatter(x, x)
# get positional data of the current axes
l, b, w, h = ax1.get_position().bounds
# add new axes on the figure at a specific location
ax2 = fig.add_axes([l+w*0.6, b+h/10, w/3, h/3])
# plot on the new axes
ax2.plot(x, x);
可以使用 pyplot 制作完全相同的图形,如下所示。
plt.scatter(x, x)
l, b, w, h = plt.gca()._position.bounds
plt.gcf().add_axes([l+w*0.6, b+h/10, w/3, h/3])
plt.plot(x, x);
add_axes
对于 OP 的颜色条从轴“窃取”空间的特定问题特别有用;因为它不是改变轴本身的位置,而是允许在其旁边添加另一个轴,可用于绘制颜色条。1
import matplotlib.pyplot as plt
data = [[0, 1, 2], [2, 0, 1]]
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.imshow(data) # without colorbar
im = ax2.imshow(data) # with colorbar
l, b, w, h = ax2.get_position().bounds # get position of `ax2`
cax = fig.add_axes([l + w + 0.03, b, 0.03, h]) # add colorbar's axes next to `ax2`
fig.colorbar(im, cax=cax)
如您所见,两个轴具有相同的尺寸。
1:这是基于我对另一个 Stack Overflow 问题的回答。