在matplotlib中垂直对齐两个绘图,前提是一个是imshow情节?

时间:2013-10-16 15:48:04

标签: python matplotlib alignment

我想对齐两个图的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 个答案:

答案 0 :(得分:15)

图像没有填满空间,因为图形的纵横比与轴不同。一种选择是更改图像的纵横比。您可以使用两个两个网格并将颜色条放在其自己的轴中来保持图像和折线图对齐。

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()

aligned image and line plot withe color bar