我用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()
结果:
现在我有了一个数组,其中包含一些矩阵单元的坐标,例如[[0,1],[0,0],[0,2] ...]。该数组是随机生成的,每次运行代码时,例如,我在数组中分配了12个单元格的坐标,而在另一个时间可能是17个,依此类推。这是一个20x20的矩阵,具有400个单元格。如何绘制坐标数组中指示的单元格的背景?
答案 0 :(得分:2)
您可以先创建一个与原始矩阵形状相同的数组,然后用零填充。然后,在坐标数组定义的位置,将其放入该数组。最后绘制该阵列,而不是原始矩阵。
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()