2017-03-28 63 views
1

我N乘N熱圖使用以下代碼創建的,例如設n是10:單行(或列)在python熱圖

random_matrix = np.random.rand(10,10) 
number = 10 
incrmnt = 1.0 
x = list(range(1,number +1)) 
plt.pcolormesh(x, x, random_matrix) 
plt.colorbar() 
plt.xlim(1, number) 
plt.xlabel('Number 1') 
plt.ylim(1, number) 
plt.ylabel('Number 2') 
plt.tick_params(
    axis = 'both', 
    which = 'both', 
    bottom = 'off', 
    top = 'off', 
    labelbottom = 'off', 
    right = 'off', 
    left = 'off', 
    labelleft = 'off') 

我想,可以添加2排熱圖一個靠近每個x軸和y軸,從row1 = np.random.rand(1,10)col1 = np.random.rand(1,10)。 這裏是我想生產什麼的示例圖像:

enter image description here

在此先感謝。

+0

還有一個非常[類似的問題(http://stackoverflow.com/questions/43073971/control-individual-linewidths-in-seaborn-heatmap)詢問如何「砍「不同地點的熱圖,以防某人感興趣。 – ImportanceOfBeingErnest

回答

1

您將創建一個子圖網格,其中子圖之間的寬度和高度比對應於相應維中的像素數。然後,您可以將相應的地塊添加到這些子地塊。在下面的代碼中,我使用了一個imshow圖,因爲我覺得在數組中每個項目有一個像素(而不是一個)更直觀。

爲了讓顏色條代表不同子圖中的顏色,可以使用提供給每個子圖的matplotlib.colors.Normalize實例以及手動創建的顏色條ScalarMappable。

enter image description here

import matplotlib 
import matplotlib.pyplot as plt 
import numpy as np 

m = np.random.rand(10,10) 
x = np.random.rand(1,m.shape[1]) 
y = np.random.rand(m.shape[0],1) 

norm = matplotlib.colors.Normalize(vmin=0, vmax=1) 
grid = dict(height_ratios=[1, m.shape[0]], width_ratios=[1,m.shape[0], 0.5 ]) 
fig, axes = plt.subplots(ncols=3, nrows=2, gridspec_kw = grid) 

axes[1,1].imshow(m, aspect="auto", cmap="viridis", norm=norm) 
axes[0,1].imshow(x, aspect="auto", cmap="viridis", norm=norm) 
axes[1,0].imshow(y, aspect="auto", cmap="viridis", norm=norm) 

axes[0,0].axis("off") 
axes[0,2].axis("off") 

axes[1,1].set_xlabel('Number 1') 
axes[1,1].set_ylabel('Number 2') 
for ax in [axes[1,1], axes[0,1], axes[1,0]]: 
    ax.set_xticks([]); ax.set_yticks([]) 

sm = matplotlib.cm.ScalarMappable(cmap="viridis", norm=norm) 
sm.set_array([]) 

fig.colorbar(sm, cax=axes[1,2]) 

plt.show() 
+0

很好,謝謝。雖然當我使用上面的代碼在我的數據方面=「自動」將每個點變成一個矩形而不是一個正方形。當我嘗試指定aspect = 1時,情節相隔太遠。有什麼建議麼? – Hia3

+0

那麼,你需要調整圖形大小和間距,以保留圖像的方面。在[其他問題](http://stackoverflow.com/questions/43073971/control-individual-linewidths-in-seaborn-heatmap)我做了一些粗略的適應。一個完美的解決方案將涉及類似於[這個問題](http://stackoverflow.com/a/43051546/4124317)。但簡單地將圖形尺寸設置爲接近陣列的方面也是足夠的,例如,如果您有5 x 20陣列,請將圖形高度設置爲寬度的四分之一。 – ImportanceOfBeingErnest