imshow and matshow
matplotlib provides two matrix visualization functions, respectively, imshow and matshow, because they are too similar, and imshow is often used as a picture display tool, so matshoww this function is basically not much known, in short, a comparison of the two as follows
import as plt import numpy as np x = (5,5) fig,axes = (1,2,figsize=(8,4)) axes[0].imshow(x) ("imshow") axes[1].matshow(x) ("matshow") plt.tight_layout() ()
However, both imshow and matshow do not show matrices, especially small matrices, perfectly, with pseudo-color correspondences and no specific values, which is of course not enough for some occasions where you need to see the actual values.
displayed value
So the next step is to write down the exact value of the matrix in a specific grid.
from itertools import product M,N = 3,6 x = (M,N) (x) for i,j in product(range(M),range(N)): (j-0.15, i, f"{x[i,j]:.2}") ()
product is a permutation iterator that groups the elements of an input sequence together two by two, thus avoiding loop nesting. The role of product is to display values, where j denotes the x coordinate and i denotes the y-axis coordinate. In the matrix index, i denotes the row number and j denotes the column number.
There is of course a problem with this picture, as the text is written horizontally, but the grid in the matrix is square, this obviously doesn't look very harmonious. It would be better to use thepcolormesh
This function, where the shape of the pixels can be changed, is clearly more appropriate.
However, there are two problems with pcolormesh, one is that the direction of the coordinate axes does not match the direction of the matrix subscripts, and the other is that the position of the coordinate labels does not refer to the middle of the grid points, and for this reason it needs to be slightly modified.
def drawMat(x, ax=None): M, N = if not ax: ax = () arrM, arrN = (M), (N) (arrM+0.5, arrM) (arrN+0.5, arrN) (x) ax.invert_yaxis() for i,j in product(range(M),range(N)): (j+0.2, i+0.55, f"{x[i,j]:.2}") () x = (5,5) drawMat(x)
Where xticks and yticks are used to remap the coordinates to map N.5 to N so that the coordinate positions are also converted to specific values, and invert_yaxis indicates that the y-axis coordinates are flipped so that the right-angle coordinate system is changed to a matrix coordinate system.
The effect is as follows
to this article on the implementation of Python matrix visualization of sample code is introduced to this article, more related python matrix visualization content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!