python - Matplotlib : Paint cells of matrix based on indexes stored in array

标签 python matplotlib matrix

我使用 Numpy 构建了一个矩阵,并为矩阵单元设置了值,并在下面的代码中使用 Matplotlib 绘制了它

import numpy as np
import matplotlib.pyplot as plt


matrix = np.loadtxt('C:\folder/matrix_values.txt', usecols=range(20))  
matrix = np.int8(matriz)


fig1, ax1 = plt.subplots()

ax1.matshow(matrix, origin='upper', alpha=0, cmap=None, interpolation='nearest')

for i in xrange(20):
    for j in xrange(20):
        value = matrix[j,i]
        ax1.text(i, j, str(value), va='center', ha='center')


tick_labels = range(20)
ax1.set_xticks([], minor=False)
ax1.set_xticks(np.arange(-.5, 20, 1), minor=True)
ax1.set_yticks([], minor=False)
ax1.set_yticks(np.arange(-.5, 20, 1), minor=True)
ax1.set_xticklabels([], minor=False)
ax1.set_xticklabels(tick_labels, minor=True)
ax1.set_yticklabels([], minor=False)
ax1.set_yticklabels(tick_labels, minor=True)
ax1.xaxis.set_ticks_position('bottom')
ax1.grid(which='minor', color='grey', linestyle='-', linewidth=1)

plt.show()

结果:

enter image description here

现在我有一个包含一些矩阵单元坐标的数组,例如 [[0,1],[0,0],[0,2]...]。该数组是随机生成的,每次运行代码时,我都会在数组中分配例如 12 个单元格的坐标,另一次可能是 17 个等。它是一个 20x20 矩阵,有 400 个单元格。如何绘制坐标数组中指示的单元格的背景?

最佳答案

您可以首先创建一个与原始矩阵形状相同的数组并用零填充它。然后,在坐标数组定义的位置处,将 1 放入该数组中。最后绘制该数组,而不是原始矩阵。

import numpy as np
import matplotlib.pyplot as plt


matrix = np.random.randint(0,9, size=(10,10))
highlight = np.array([[1,3],[4,2],[6,8],[7,2]])

hm = np.zeros_like(matrix)
hm[highlight[:,1],highlight[:,0]] = 1

fig, ax = plt.subplots()

ax.matshow(hm, origin='upper', alpha=1, vmin=0, vmax=2, cmap="Blues")

for i in range(matrix.shape[1]):
    for j in range(matrix.shape[1]):
        ax.text(i, j, str(matrix[j,i]), va='center', ha='center')

n = min(matrix.shape)+1
tick_labels = range(n)
ax.set_xticks([], minor=False)
ax.set_xticks(np.arange(-.5, n-1, 1), minor=True)
ax.set_yticks([], minor=False)
ax.set_yticks(np.arange(-.5, n-1, 1), minor=True)
ax.set_xticklabels([], minor=False)
ax.set_xticklabels(tick_labels, minor=True)
ax.set_yticklabels([], minor=False)
ax.set_yticklabels(tick_labels, minor=True)
ax.xaxis.set_ticks_position('bottom')
ax.grid(which='minor', color='grey', linestyle='-', linewidth=1)

plt.show()

enter image description here

关于python - Matplotlib : Paint cells of matrix based on indexes stored in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710762/

相关文章:

python - 如何在类范围之外访问变量定义的浏览按钮类

python-3.x - seaborn histplot 和 displot 输出不匹配

c++ - 正确访问 const 一行特征矩阵

c++ - 如何在 openGL 中乘以矩阵

python - 如果某些行的列中的值丢失,如何应用 TextBlob?

python - Crontab 不执行 Python 脚本?

python - 使用 tweepy 按日期获取推文

python - 不一致的刻度标签字体与 matplotlib 子图

python-3.x - key 错误 : 'axes.color_cycle is not a valid rc parameter (see rcParams.keys() for a list of valid parameters)'

r - 设置行和列的名称?