显示矩阵值和色彩映射

时间:2016-11-30 11:56:41

标签: python matrix matplotlib imshow

我需要使用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

2 个答案:

答案 0 :(得分:14)

您需要使用ax.matshow而不是plt.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

答案 1 :(得分:2)

在Jupyter笔记本中,使用DataFrames和Seaborn也可以做到这一点:

import numpy as np
import seaborn as sns
import pandas as pd

min_val, max_val = 0, 15
intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val))
cm = sns.light_palette("blue", as_cmap=True)
x=pd.DataFrame(intersection_matrix)
x=x.style.background_gradient(cmap=cm)
display(x)

enter image description here