2014-02-11 244 views
12

我想在Matplotlib中使用imshowmatshow創建一個10x10網格。下面的函數將numpy數組作爲輸入,並繪製網格圖。但是,我想從陣列中的值也顯示在網格定義的單元格內。到目前爲止,我找不到一個正確的方法來做到這一點。我可以使用plt.text將東西放在網格上,但這需要每個單元的座標,完全不方便。有沒有更好的方式去做我想要完成的事情?Matplotlib imshow/matshow在地圖上顯示值

謝謝!

注意:下面的代碼沒有從數組中取值,我只是在玩plt.text

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

board = np.zeros((10, 10)) 

def visBoard(board): 
    cmap = colors.ListedColormap(['white', 'red']) 
    bounds=[0,0.5,1] 
    norm = colors.BoundaryNorm(bounds, cmap.N) 
    plt.figure(figsize=(4,4)) 
    plt.matshow(board, cmap=cmap, norm=norm, interpolation='none', vmin=0, vmax=1) 
    plt.xticks(np.arange(0.5,10.5), []) 
    plt.yticks(np.arange(0.5,10.5), []) 
    plt.text(-0.1, 0.2, 'x') 
    plt.text(0.9, 0.2, 'o') 
    plt.text(1.9, 0.2, 'x') 
    plt.grid() 

    visBoard(board) 

輸出:

enter image description here

+1

使用批註可以讓您非常靈活地指定文本的座標。 – tacaswell

+0

我想知道是否有辦法做到這一點,而不指定座標。到目前爲止,我手動完成了它(可能不是最聰明的想法)假設數字大小可能會改變,我將不得不提出一個計算正確座標的函數。 – marillion

回答

21

你可以這樣做:

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val = 0, 10 
ind_array = np.arange(min_val + 0.5, max_val + 0.5, 1.0) 
x, y = np.meshgrid(ind_array, ind_array) 

for i, (x_val, y_val) in enumerate(zip(x.flatten(), y.flatten())): 
    c = 'x' if i%2 else 'o' 
    ax.text(x_val, y_val, c, va='center', ha='center') 
#alternatively, you could do something like 
#for x_val, y_val in zip(x.flatten(), y.flatten()): 
# c = 'x' if (x_val + y_val)%2 else 'o' 

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


編輯:

以下是帶有imshow背景的更新示例。

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val, diff = 0., 10., 1. 

#imshow portion 
N_points = (max_val - min_val)/diff 
imshow_data = np.random.rand(N_points, N_points) 
ax.imshow(imshow_data, interpolation='nearest') 

#text portion 
ind_array = np.arange(min_val, max_val, diff) 
x, y = np.meshgrid(ind_array, ind_array) 

for x_val, y_val in zip(x.flatten(), y.flatten()): 
    c = 'x' if (x_val + y_val)%2 else 'o' 
    ax.text(x_val, y_val, c, va='center', ha='center') 

#set tick marks for grid 
ax.set_xticks(np.arange(min_val-diff/2, max_val-diff/2)) 
ax.set_yticks(np.arange(min_val-diff/2, max_val-diff/2)) 
ax.set_xticklabels([]) 
ax.set_yticklabels([]) 
ax.set_xlim(min_val-diff/2, max_val-diff/2) 
ax.set_ylim(min_val-diff/2, max_val-diff/2) 
ax.grid() 
plt.show() 

enter image description here

+0

謝謝!我將嘗試對此進行迭代。我必須使用imshow/matshow繪圖作爲基礎,因爲它會顯示熱圖。我打算在熱圖上有值。不過,我想我可以覆蓋你在imshow/matshow圖上的內容。讓我們試試... – marillion

+0

@marillion,檢查編輯。 – wflynny

+0

感謝您的代碼!請注意,最終的圖像可能會倒過來顯示。根據您提供給['imshow']的參數,可以通過交換set_ylim:ax.set_ylim(bottom = max_val - diff/2,top = min_val - diff/2) –

2

爲了您的圖形,你應該應該嘗試與pyplot.table

import matplotlib.pyplot as plt 
import numpy as np 

board = np.zeros((10, 10)) 
board[0,0] = 1 
board[0,1] = -1 
board[0,2] = 1 
def visBoard(board): 
    data = np.empty(board.shape,dtype=np.str) 
    data[:,:] = ' ' 
    data[board==1.0] = 'X' 
    data[board==-1.0] = 'O' 
    plt.axis('off') 
    size = np.ones(board.shape[0])/board.shape[0] 
    plt.table(cellText=data,loc='center',colWidths=size,cellLoc='center',bbox=[0,0,1,1]) 
    plt.show() 

visBoard(board) 
+0

有沒有辦法將這張表覆蓋在imshow/matshow圖上?我必須保留那些將被用作熱圖的東西。我只需要將'x''o'覆蓋在它上面。 – marillion

+0

是的,我可以做一些類似於plt的事情。繪圖(範圍(10),範圍(10))',我看到表格下方的圖表,表格就像另一個圖表。 –

2

上@wflynny的代碼一些闡述使它成爲可以接收任意矩陣不管是什麼尺寸的功能並繪製其價值。

import numpy as np 
import matplotlib.pyplot as plt 

cols = np.random.randint(low=1,high=30) 
rows = np.random.randint(low=1,high=30) 
X = np.random.rand(rows,cols) 

def plotMat(X): 
    fig, ax = plt.subplots() 
    #imshow portion 
    ax.imshow(X, interpolation='nearest') 
    #text portion 
    diff = 1. 
    min_val = 0. 
    rows = X.shape[0] 
    cols = X.shape[1] 
    col_array = np.arange(min_val, cols, diff) 
    row_array = np.arange(min_val, rows, diff) 
    x, y = np.meshgrid(col_array, row_array) 
    for col_val, row_val in zip(x.flatten(), y.flatten()): 
     c = '+' if X[row_val.astype(int),col_val.astype(int)] < 0.5 else '-' 
     ax.text(col_val, row_val, c, va='center', ha='center') 
    #set tick marks for grid 
    ax.set_xticks(np.arange(min_val-diff/2, cols-diff/2)) 
    ax.set_yticks(np.arange(min_val-diff/2, rows-diff/2)) 
    ax.set_xticklabels([]) 
    ax.set_yticklabels([]) 
    ax.set_xlim(min_val-diff/2, cols-diff/2) 
    ax.set_ylim(min_val-diff/2, rows-diff/2) 
    ax.grid() 
    plt.show() 

plotMat(X)