display matrix values and colormap

fremorie picture fremorie · Nov 30, 2016 · Viewed 28.6k times · Source

I need to display values of my matrix using matshow. However, with the code I have now I just get two matrices - one with values and other colored. How do I impose them? Thanks :)

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()

Output:

enter image description here enter image description here

Answer

tmdavison picture tmdavison · Nov 30, 2016

You need to use ax.matshow not plt.matshow to make sure they both appear on the same axes.

If you do that, you also don't need to set the axes limits or ticks.

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')

Here I have created some random data as I don't have your matrix. Note that I had to change the ordering of the index for the text label to [j,i] rather than [i][j] to align the labels correctly.

enter image description here