2016-11-30 107 views
0

我需要使用matshow显示我的矩阵的值。 但是,通过我现在的代码,我只能得到两个矩阵 - 一个具有值和其他颜色。 我该如何强加它们?谢谢:)显示矩阵值和颜色地图

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val = 0, 15 

for i in xrange(15): 
    for j in xrange(15): 
     c = intersection_matrix[i][j] 
     ax.text(i+0.5, j+0.5, str(c), va='center', ha='center') 

plt.matshow(intersection_matrix, cmap=plt.cm.Blues) 

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 enter image description here

回答

3

您需要使用ax.matshowplt.matshow,以确保它们都出现在同一轴上。

如果你这样做,你也不需要设置轴限制或滴答。

import numpy as np 
import matplotlib.pyplot as plt 

fig, ax = plt.subplots() 

min_val, max_val = 0, 15 

intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val)) 

ax.matshow(intersection_matrix, cmap=plt.cm.Blues) 

for i in xrange(15): 
    for j in xrange(15): 
     c = intersection_matrix[j,i] 
     ax.text(i, j, str(c), va='center', ha='center') 

这里我创建了一些随机数据,因为我没有矩阵。请注意,我必须将文本标签的索引顺序更改为[j,i]而不是[i][j]才能正确对齐标签。

enter image description here

+0

非常感谢! :)你能解释一下你改变文本标签索引顺序的步骤吗?为什么有必要改变'i'和'j'? – fremorie

+0

它与你是否正在考虑将数组索引作为C排序或FORTRAN排序。你可以在这里阅读:https://docs.scipy.org/doc/numpy/reference/internals.html#multidimensional-array-indexing-order-issues – tom