I want to align the x-axis of two plots, provided one is an imshow
plot.
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')
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With