gpt4 book ai didi

python - Matplotlib imshow/matshow 在图上显示值

转载 作者:太空狗 更新时间:2023-10-29 17:13:41 28 4
gpt4 key购买 nike

我正在尝试在 Matplotlib 中使用 imshowmatshow 创建一个 10x10 网格。下面的函数将一个 numpy 数组作为输入,并绘制网格。但是,我希望数组中的值也显示在网格定义的单元格内。到目前为止,我找不到合适的方法来做到这一点。我可以使用 plt.text 在网格上放置东西,但这需要每个单元格的坐标,完全不方便。有没有更好的方法来完成我想要完成的事情?

谢谢!

注意:下面的代码还没有从数组中获取值,我只是在玩 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

最佳答案

你能不能做这样的事:

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

关于python - Matplotlib imshow/matshow 在图上显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21712047/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com