Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display matrix values and colormap

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

like image 305
fremorie Avatar asked Nov 30 '16 11:11

fremorie


People also ask

What is MatPlotLib default colormap?

Colormap. The new default colormap used by matplotlib. cm. ScalarMappable instances is 'viridis' (aka option D).

What is Matshow?

matshow (A, fignum=None, **kwargs)[source] Display an array as a matrix in a new figure window. The origin is set at the upper left hand corner and rows (first dimension of the array) are displayed horizontally.

How do I make a table in MatPlotLib?

To add a table on the axis, use table() instance, with column text, column labels, columns, and location=center. To display the figure, use show() method.


1 Answers

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

like image 103
tmdavison Avatar answered Sep 20 '22 04:09

tmdavison