Matplotlib:使用 imshow 显示数组值

Matplotlib : display array values with imshow

我正在尝试使用 matplotlib 函数创建网格,例如 imshow
来自这个数组:

[[ 1  8 13 29 17 26 10  4],
[16 25 31  5 21 30 19 15]]

我想在同一网格上将值绘制为颜色和文本值本身 (1,2, ...)。这是我目前所拥有的(我只能绘制与每个值关联的颜色):

from matplotlib import pyplot
import numpy as np

grid = np.array([[1,8,13,29,17,26,10,4],[16,25,31,5,21,30,19,15]])
print 'Here is the array'
print grid

fig1, (ax1, ax2)= pyplot.subplots(2, sharex = True, sharey = False)
ax1.imshow(grid, interpolation ='none', aspect = 'auto')
ax2.imshow(grid, interpolation ='bicubic', aspect = 'auto')
pyplot.show()   

您想遍历 grid 中的值,并使用 ax.text 将标签添加到图中。

幸运的是,对于二维数组,numpyndenumerate,这使得这很简单:

for (j,i),label in np.ndenumerate(grid):
    ax1.text(i,j,label,ha='center',va='center')
    ax2.text(i,j,label,ha='center',va='center')

如果出于任何原因您必须使用 imshow 自然提供的 不同的范围 ,则以下方法(即使更人为)会执行工作:

size = 4
data = np.arange(size * size).reshape((size, size))

# Limits for the extent
x_start = 3.0
x_end = 9.0
y_start = 6.0
y_end = 12.0

extent = [x_start, x_end, y_start, y_end]

# The normal figure
fig = plt.figure(figsize=(16, 12))
ax = fig.add_subplot(111)
im = ax.imshow(data, extent=extent, origin='lower', interpolation='None', cmap='viridis')

# Add the text
jump_x = (x_end - x_start) / (2.0 * size)
jump_y = (y_end - y_start) / (2.0 * size)
x_positions = np.linspace(start=x_start, stop=x_end, num=size, endpoint=False)
y_positions = np.linspace(start=y_start, stop=y_end, num=size, endpoint=False)

for y_index, y in enumerate(y_positions):
    for x_index, x in enumerate(x_positions):
        label = data[y_index, x_index]
        text_x = x + jump_x
        text_y = y + jump_y
        ax.text(text_x, text_y, label, color='black', ha='center', va='center')

fig.colorbar(im)
plt.show()

如果您想放置其他类型的数据而不一定是您用于图像的值,您可以按以下方式修改上面的脚本(在数据后添加值):

size = 4
data = np.arange(size * size).reshape((size, size))
values = np.random.rand(size, size)

# Limits for the extent
x_start = 3.0
x_end = 9.0
y_start = 6.0
y_end = 12.0

extent = [x_start, x_end, y_start, y_end]

# The normal figure
fig = plt.figure(figsize=(16, 12))
ax = fig.add_subplot(111)
im = ax.imshow(data, extent=extent, origin='lower', interpolation='None', cmap='viridis')

# Add the text
jump_x = (x_end - x_start) / (2.0 * size)
jump_y = (y_end - y_start) / (2.0 * size)
x_positions = np.linspace(start=x_start, stop=x_end, num=size, endpoint=False)
y_positions = np.linspace(start=y_start, stop=y_end, num=size, endpoint=False)

for y_index, y in enumerate(y_positions):
    for x_index, x in enumerate(x_positions):
        label = values[y_index, x_index]
        text_x = x + jump_x
        text_y = y + jump_y
        ax.text(text_x, text_y, label, color='black', ha='center', va='center')

fig.colorbar(im)
plt.show()