2016-07-26 34 views
0

matshow和colorbar對象不填充gridspec單元內的同一空間,因此它們的高度不同。在gridspec單元內調整matplotlib對象(matshow和colorbar大小不匹配)

通常我會用彩條「縮水」的說法,但是這似乎並沒有嵌套在gridspec對象時工作

我怎麼能縮小彩條對象不調整的matshow熱圖?

在此先感謝

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib import gridspec 

df = pd.DataFrame((np.random.randint(0, 3, 10000).reshape(100, 100))) 
fig = plt.figure(figsize=(15,15)) 
gs = gridspec.GridSpec(10, 10) 

#### other axes removed for simplicity 

ax2 = fig.add_subplot(gs[2:,:8]) 

# plot heatmap 
cax = ax2.matshow(df, interpolation='nearest', cmap=plt.cm.YlGn, aspect='equal') 
ax2.set_xticks([]) 
ax2.set_yticks([]) 

ax3 = fig.add_subplot(gs[2:,8]) 

fig.colorbar(cax, cax=ax3) 

plt.tight_layout() 
gs.update(wspace=2, hspace=0.1) 
plt.show() 

matshow and colorbar are slightly (annoyingly) different heights

編輯:標註的圖像澄清

enter image description here

+0

熱圖和彩'是不同的高度'。在你附上的圖片中,他們看起來和我一樣高。你能澄清你的意思嗎? – DavidG

+0

他們非常接近但不完全相同! 我已添加另一張圖片來澄清 – JoshuaBox

回答

2

你可以使用matplotlib AxesDivider。下面是使用從你的問題中的數據爲例:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from matplotlib import gridspec 

fig = plt.figure(figsize=(15,15)) 
df = pd.DataFrame((np.random.randint(0, 3, 10000).reshape(100, 100))) 
gs = gridspec.GridSpec(10, 10) 
ax2 = fig.add_subplot(gs[2:,:8]) 

im = ax2.matshow(df,interpolation='nearest',cmap=plt.cm.YlGn, aspect='equal') 

divider = make_axes_locatable(ax2) 
cax = divider.append_axes("right", size="5%", pad=0.05) 

plt.colorbar(im, cax=cax) 
plt.show() 

這將產生如下圖,這在我的眼睛看起來他們是相同的尺寸:

enter image description here

+0

非常感謝!正是我需要的 – JoshuaBox

相關問題