python uses matplotlib to draw matrices using matshow() to draw matrix graphs

  This demonstration uses jupter notebook.

1. Draw plt.cm

    Example 1: Set a 10*10 matrix from 0-100

Code 1:

import matplotlib.pyplot as plt
import numpy as np
A = np.arange(0, 100).reshape(10, 10)
plt.matshow(mat, cmap=plt.cm.Reds)#这里设置颜色为红色,也可以设置其他颜色
plt.title("matrix A")
plt.show()

The following results are obtained in Figure 1:

     Note: There are many color settings for the matrix. You can change the Reds in plt.matshow(mat, cmap=plt.cm.Reds) to set other colors according to your own preferences. Several other colors are given below.

Code 2: (Set color to blue)

import matplotlib.pyplot as plt
import numpy as np
A = np.arange(0, 100).reshape(10, 10)
plt.matshow(mat, cmap=plt.cm.Blues)
plt.title("matrix A")
plt.show()

Result 2:

 Code 3: (set color gray)

import matplotlib.pyplot as plt
import numpy as np
A = np.arange(0, 100).reshape(10, 10)
plt.matshow(mat, cmap=plt.cm.gray)
plt.title("matrix A")
plt.show()

Result 3:

   Example 2: Randomly set matrix A

Code 4:

import matplotlib.pyplot as plt
import numpy as np
A=np.array([[4,3,2,4],[5,4,7,8],[9,16,11,5],[13,3,4,16],[6,18,1,20]])
plt.matshow(X, cmap=plt.cm.Reds)
plt.title("matrix A")
plt.show()

Result 4:

    Note: As can be seen from the picture, the depth of red is different for different numerical values. The larger the numerical value, the darker the red color. You can also set different colors according to your own preferences, so I won’t show too much.

2. Use plt.colorbar to draw a matrix diagram

Code 5:

import numpy as np
import matplotlib.pyplot as plt
X=np.array([[0,3,2,4],[5,4,7,8],[9,16,8,5],[13,3,4,16],[6,18,1,20]])
A = np.arange(0, 100).reshape(10, 10)
ax = plt.matshow(X)
plt.colorbar(ax.colorbar, fraction=0.025)
plt.title("matrix X");
plt.show()

Result 5:

Some of the notes I took during my study may have some shortcomings in the article. Everyone is welcome to discuss and correct me. 

おすすめ

転載: blog.csdn.net/weixin_50040016/article/details/119601110