2014-01-08 36 views
5

我米試圖產生用於一些數據熱圖顯示在網格中的值和我的代碼如下所示:使用matplotlib

data = [['basis', 2007, 2008], 
     [1, 2.2, 3.4], 
     [2, 0, -2.2], 
     [3, -4.1, -2.5], 
     [4, -5.8, 1.2], 
     [5, -5.4, -3.6], 
     [6, 1.4, -5.9]] 

x_header = data[0][1:] 
y_header = [i for i in range(1, 13)] 
data=data[1:] 
for i in range(len(data)): 
    data[i] = data[i][1:] 
arr = np.array(data) 
fig, ax = plt.subplots() 
#heatmap = plt.pcolor(arr, cmap = 'RdBu') 
norm = MidpointNormalize(midpoint=0) 
im = ax.imshow(data, norm=norm, cmap=plt.cm.seismic, interpolation='none') 

ax.set_xticks(np.arange(arr.shape[1]), minor=False) 
ax.set_yticks(np.arange(arr.shape[0]), minor=False) 
ax.xaxis.tick_top() 
ax.set_xticklabels(x_header, rotation=90) 
ax.set_yticklabels(y_header) 

fig.colorbar(im) 
plt.show() 

它生成圖像

enter image description here

我還想要在網格中顯示值。有沒有辦法做到這一點?

回答

9

當然,僅僅這樣做:

import matplotlib.pyplot as plt 
import numpy as np 

data = np.random.random((4, 4)) 

fig, ax = plt.subplots() 
# Using matshow here just because it sets the ticks up nicely. imshow is faster. 
ax.matshow(data, cmap='seismic') 

for (i, j), z in np.ndenumerate(data): 
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center') 

plt.show() 

enter image description here

然而,標籤是很難看到,所以您可能希望他們周圍的框:

import matplotlib.pyplot as plt 
import numpy as np 

data = np.random.random((4, 4)) 

fig, ax = plt.subplots() 
# Using matshow here just because it sets the ticks up nicely. imshow is faster. 
ax.matshow(data, cmap='seismic') 

for (i, j), z in np.ndenumerate(data): 
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center', 
      bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3')) 

plt.show() 

enter image description here

此外,在很多情況下,ax.annotate更有用ax.text。在如何放置文本方面它更加靈活,但也更加複雜。看看這裏的例子:http://matplotlib.org/users/annotations_guide.html

+0

非常感謝,這正是我所需要的。 –

+2

只要記錄您應該也能夠使用'ax.table'來達到類似的結果。 –