2017-06-21 45 views
0

我想分享一個imshow這是方形的x軸和克拉西克情節:對齊插曲用彩條

  1. 的imshow必須是方形
  2. 用彩條
  3. 情節波紋管應該共享相同的軸(或至少看起來像對齊imshow)

我花了兩天時間,現在我瘋了。有人知道如何對齊它們嗎?

square imshow on the top, with a color bar, and bellow a plot, that should share the same axis

用於產生圖像的代碼是波紋管。

def myplot(Nbin=20): 

X = np.random.rand(1000) 
Y = np.random.rand(1000) 
h2, yh2, xh2 = np.histogram2d(Y, X, bins=[Nbin,Nbin]) 
h1, xh1 = np.histogram(X, bins=Nbin) 
###################################### 
###################################### 
fig = plt.figure() 
gs = gridspec.GridSpec(3, 2) 
###################################### 
###################################### 
ax1 = plt.subplot(gs[:-1,:]) 
im = plt.imshow(h2, interpolation='nearest', origin='lower', 
       extent=[xh2[0],xh2[-1],yh2[0],yh2[-1]]) 
cb = plt.colorbar(im, ax=ax1) 
plt.xlim(xh1[0], xh1[-1]) 
plt.ylim(xh1[0], xh1[-1]) 
ax1.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='off') 
###################################### 
###################################### 
ax2 = plt.subplot(gs[-1,:]) 
plt.plot(xh1[:-1] + np.diff(xh1)/2., h1) 
plt.xlim(xh1[0], xh1[-1]) 
cm = plt.cm.Blues 
cb2 = plt.colorbar(ax=ax2) 
ax2.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='on') 
###################################### 
###################################### 
fig.tight_layout() 
fig.subplots_adjust(hspace=0.05) 
cb2.ax.set_visible(False) 

回答

2

我能想象的最簡單的方法有直接的圖像下方的第二軸是用mpl_toolkits.axes_grid1.make_axes_locatable。這允許以犧牲新創建的副圖來縮小圖像,並且同樣可以用於定位顏色條。

import numpy as np 
import matplotlib.pyplot as plt 
from mpl_toolkits.axes_grid1 import make_axes_locatable 

Nbin=20 

X = np.random.rand(1000) 
Y = np.random.rand(1000) 
h2, yh2, xh2 = np.histogram2d(Y, X, bins=[Nbin,Nbin]) 
h1, xh1 = np.histogram(X, bins=Nbin) 

fig = plt.figure() 


ax1 = plt.subplot(111) 
im = ax1.imshow(h2, interpolation='nearest', origin='lower', 
       extent=[xh2[0],xh2[-1],yh2[0],yh2[-1]]) 

plt.xlim(xh1[0], xh1[-1]) 
plt.ylim(xh1[0], xh1[-1]) 
ax1.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='off') 


divider = make_axes_locatable(ax1) 
ax2 = divider.append_axes("bottom", size="50%", pad=0.08) 
cax = divider.append_axes("right", size="5%", pad=0.08) 
cb = plt.colorbar(im, ax=ax1, cax=cax) 

#ax2 = plt.subplot(gs[-1,:]) # , sharex=ax1 
ax2.plot(xh1[:-1] + np.diff(xh1)/2., h1) 
ax2.set_xlim(xh1[0], xh1[-1]) 
cm = plt.cm.Blues 

ax2.tick_params(axis='x', which='both', bottom='on', top='on', labelbottom='on') 

plt.show() 

enter image description here