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:
Colormap. The new default colormap used by matplotlib. cm. ScalarMappable instances is 'viridis' (aka option D).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With