2016-11-30 108 views
0

我需要使用matshow顯示我的矩陣的值。 但是,通過我現在的代碼,我只能得到兩個矩陣 - 一個具有值和其他顏色。 我該如何強加它們?謝謝:)顯示矩陣值和顏色地圖

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val = 0, 15 

for i in xrange(15): 
    for j in xrange(15): 
     c = intersection_matrix[i][j] 
     ax.text(i+0.5, j+0.5, str(c), va='center', ha='center') 

plt.matshow(intersection_matrix, cmap=plt.cm.Blues) 

ax.set_xlim(min_val, max_val) 
ax.set_ylim(min_val, max_val) 
ax.set_xticks(np.arange(max_val)) 
ax.set_yticks(np.arange(max_val)) 
ax.grid() 

輸出:

enter image description here enter image description here

回答

3

您需要使用ax.matshowplt.matshow,以確保它們都出現在同一軸上。

如果你這樣做,你也不需要設置軸限制或滴答。

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val = 0, 15 

intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val)) 

ax.matshow(intersection_matrix, cmap=plt.cm.Blues) 

for i in xrange(15): 
    for j in xrange(15): 
     c = intersection_matrix[j,i] 
     ax.text(i, j, str(c), va='center', ha='center') 

這裏我創建了一些隨機數據,因爲我沒有矩陣。請注意,我必須將文本標籤的索引順序更改爲[j,i]而不是[i][j]才能正確對齊標籤。

enter image description here

+0

非常感謝! :)你能解釋一下你改變文本標籤索引順序的步驟嗎?爲什麼有必要改變'i'和'j'? – fremorie

+0

它與你是否正在考慮將數組索引作爲C排序或FORTRAN排序。你可以在這裏閱讀:https://docs.scipy.org/doc/numpy/reference/internals.html#multidimensional-array-indexing-order-issues – tom