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

2024-06-13 10:05:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对齐两个图的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高。如果我把色条拿出来,它们看起来是对齐的,但我还是不能把它们放在一起。我也想要彩色条。


Tags: importgsmatplotlibasnppltrandomv2
1条回答
网友
1楼 · 发布于 2024-06-13 10:05:02

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

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

相关问题 更多 >