如何在matplotlib中将两个图纵向对齐,其中一个是imshow图?

6

我想对齐两个图表的x轴,其中一个是imshow图表。

我尝试使用gridspec,如下所示:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as grd

v1 = np.random.rand(50,150)
v2 = np.random.rand(150)

fig = plt.figure()

gs = grd.GridSpec(2,1,height_ratios=[1,10],wspace=0)


ax = plt.subplot(gs[1])
p = ax.imshow(v1,interpolation='nearest')
cb = plt.colorbar(p,shrink=0.5)
plt.xlabel('Day')
plt.ylabel('Depth')
cb.set_label('RWU')
plt.xlim(1,140)

#Plot 2
ax2 = plt.subplot(gs[0])
ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
x=np.arange(1,151,1)
ax2.plot(x,v2,'k',lw=0.5)
plt.xlim(1,140)
plt.ylim(0,1.1)
#
plt.savefig("ex.pdf", bbox_inches='tight') 

我希望图形之间尽可能靠近,且一个图形的高度是另一个图形的1/10。如果我将颜色条去掉,它们似乎对齐了,但仍然无法使它们彼此靠近。我还希望保留颜色条。
1个回答

20

图片未填满空间是因为图形的宽高比与坐标轴不同。一种解决方法是改变您图片的宽高比。您可以使用2x2网格并将色条放在自己的坐标轴中,从而保持图像和折线图对齐。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as grd

v1 = np.random.rand(50,150)
v2 = np.random.rand(150)

fig = plt.figure()

# create a 2 X 2 grid 
gs = grd.GridSpec(2, 2, height_ratios=[1,10], width_ratios=[6,1], wspace=0.1)

# image plot
ax = plt.subplot(gs[2])
p = ax.imshow(v1,interpolation='nearest',aspect='auto') # set the aspect ratio to auto to fill the space. 
plt.xlabel('Day')
plt.ylabel('Depth')
plt.xlim(1,140)

# color bar in it's own axis
colorAx = plt.subplot(gs[3])
cb = plt.colorbar(p, cax = colorAx)
cb.set_label('RWU')

# line plot
ax2 = plt.subplot(gs[0])

ax2.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.xaxis.set_ticks_position('bottom')
ax2.yaxis.set_ticks_position('left')
ax2.set_yticks([0,1])
x=np.arange(1,151,1)
ax2.plot(x,v2,'k',lw=0.5)
plt.xlim(1,140)
plt.ylim(0,1.1)

plt.show()

对齐的图像和带有色条的折线图


谢谢你,@Molly。现在我明白如何管理这个图表并更改其他参数了。 - Marcos Alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接