我想对齐两个图的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。如果我取出颜色条,它们似乎对齐,但仍然不能将它们彼此靠近。我也想要颜色条。
图像没有填满空间,因为图形的长宽比与轴不同。一种选择是更改图像的纵横比。您可以使用二乘二网格并在其自己的轴上放置颜色条,以使图像和折线图对齐。
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句