Reputation: 357
I have two ndarrays: Mat, labels Currently I display Mat:
plt.imshow(Mat, cmap='gray', vmin=0, vmax=1, interpolation='None')
labels has the same shape as Mat, and lables[(i,j)] contains a label of Mat[(i,j)]. How can I show the label on each pixel?
Upvotes: 5
Views: 7204
Reputation: 80339
The easiest approach uses Seaborn's heatmap. When annot=True
it prints the data values into the cells. But annot=
can also be a matrix of labels. In that case it is important to set the print format to string (fmt='s'
). annot_kws=
can set additional keywords, such as fontsize or color. x
and yticklabels
can be incorporated in the call to heatmap()
, or be set afterwards using matplotlib.
An important benefit of the default coloring is that Sorn uses black on the light colored cells and white on the dark cells.
Here is an example that uses some utf8 characters as labels.
from matplotlib import pyplot as plt
import numpy as np
import seaborn as sns
M, N = 5, 10
mat = np.random.rand(M, N)
labels = np.random.choice(['X', '☀', '★', '♛'], size=(M, N))
ax = sns.heatmap(mat, cmap="inferno", annot=labels, annot_kws={'fontsize': 16}, fmt='s')
plt.show()
PS: There is a matplotlib example in the documentation to create something similar without Seaborn. It can be easily adapted to print strings from a different matrix, and also a test can be added to change the color depending on the cell darkness.
Upvotes: 8