垂直对齐两地块在matplotlib提供的一个是imshow情节?地块、情节、matplotlib、imshow

2023-09-11 07:49:17 作者:十里柔情

我要对齐的两个地块的X轴,提供的一个是 imshow 的情节。

I want to align the x-axis of two plots, provided one is an imshow plot.

我曾尝试使用 gridspec ,因为它如下:

I have tried to use gridspec as it follows:

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高度的曲线。如果我参加了彩条了,他们似乎对齐,但还是不能把它们彼此接近。我也想太多的彩条。

I also want the plots as close as possible to each other and one 1/10 the height of the other. If I take the colorbar out, they seem to aligned but still I can't put them close to each other. I also want the colorbar too.

推荐答案

图片未填满的空间,因为该图的纵横比小于轴不同。一种选择是改变图像的宽高比。可以保持图像,并通过使用两个两个网格,把在它自己的轴色条对齐的线图。

The image isn't filling up the space because the aspect ratio of the figure is different than axis. One option is to change the aspect ratio of your image. You can keep the image and the line graph aligned by using a two by two grid and putting the color bar in it's own axis.

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