0 Overview
Firstly, establish the canvas and recommend using fig, ax= Plt. subplots , assign all drawing tasks to the ax object. Note that unless a 1 * 1 canvas partition is used, ax will be a two-dimensional array and different positions of ax objects need to be obtained in the form of an array.
1. Important factors for adjusting external auxiliary lines and legends in images
- Main title
fig.suptitle("title") - Subtitle
ax.set_title("title) - Axis labels
ax.set_xlabel([array]) ax.set_ylabel([array]) - Coordinate axis display range
ax.set_xlim([lower, upper]) ax.set_ylim([lower, upper]) - Axis position
ax.spines["left|top|right|bottom"].set_position(("data|outward,axes",value)) - Coordinate axis display
ax.spines["left|top|right|bottom"].set_visible(True|False) - Axis color
ax.spines["left|top|right|bottom"].set_color(“color”) - Legend
ax.legend(loc="upper right|upper left}bottom left| bottom right| left|right|top|bottom|best")
This property requires defining label variables in each image curve - Grid Ax. grid (alpha= 0.5) alpha sets transparency
- Log coordinate display
ax.set_xscale('log')
ax.set_yscale('log')
Example, drawing sigmoid function.
from matplotlib import pyplot as plt
%matplotlib inline
sigma_x = np.arange(-10,10,0.1)
sigma_y = 1 /(1 + np.power(np.e, -sigma_x))
fig, ax = plt.subplots(1,1,figsize=(12,4),facecolor='whitesmoke', edgecolor='gray')
ax.plot(sigma_x, sigma_y, lw=1, ls= '-', color='blue',label="sigmoid core function")
fig.suptitle("title")
ax.legend(loc="upper left")
ax.set_xlabel("t")
ax.set_ylabel("sigmoid")
ax.set_xticks(np.arange(-10,10.1,5))
ax.set_yticks(np.arange(0,1.2,0.2))
ax.set_xlim(-10,10)
ax.set_ylim(-0.1,1.1)
ax.set_title('sigmoid function show')
ax.axhline(0, color='grey', linewidth=1)
ax.axvline(0, color='grey', linewidth=1)
ax.hlines(0.5,-12,12, ls=':', color='gray')
ax.hlines(1.0,-12,12, ls=':', color='gray')
plt.show()

- The complete code can be found here (GitHub repository)
2. Important factors for adjusting the internal lines of an image
- Draw horizontal and vertical auxiliary lines
ax.hlines(y,x_left,x_right, ls=':', color='gray')
ax.vlines(x,y_bottom,y_up, ls=':', color='gray') - Draw the horizontal and vertical axes
ax.axhline(pos, color='grey', linewidth=1)
ax.axvline(pos, color='grey', linewidth=1) - Draw different curves
ax.polt()
ax.scatter() - Fill the middle position of the curve
ax.fill_between(x,y1,y2) - Add curve annotations
plt.annotate(text ,xy,xytext,arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)
Xy represents arrow position, xytext represents text position
ax.text(s,x,y,fontsize,color)
The above two functions are often used together with the for loop
Annotate Example.
x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x),c = '#0ffef9',label = 'sin(x)')
plt.annotate(text = 'bottom point',xy = (4.65,-1),xytext = (4.2,0),
arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)
plt.show()

Example, knn grouping.
from matplotlib import pyplot as plt
import matplotlib
plt.rcParams['font.sans-serif']=['SimHei'] #specify default font SimHei for blackbody
plt.rcParams['axes.unicode_minus']=False #used to display negative signs normally
colors = ['red', 'purple', 'blue', 'green', 'lime']
shapes = ['+', 'o', '>', '*', '.']
# create 5 different list containing 5 classes of points
upper_list = []
for i in range(k):
new_list = []
upper_list.append(new_list)
# assign each point into its corresponding class
data_with_lab = zip(data, label)
for dat, lab in data_with_lab:
for i in range(k):
if lab == i:
upper_list[i].append(dat.tolist())
fig, ax = plt.subplots(1,1,facecolor='whitesmoke',edgecolor='grey',
dpi=120,figsize=(8,6))
#fig.suptitle("knn results visualization",fontsize=18, color='red')
ax.set_title('knn with groups')
for i in range(k):
ax.scatter(np.array(upper_list[i])[:,0],
np.array(upper_list[i])[:,1],
color=colors[i],
marker=shapes[i],
label="class-"+str(i))
# plot the unassigned point
ax.plot(target[0],target[1],color='black',marker='<',label="untold")
ax.text(target[0]-1.8,target[1]+1.2,
'class-'+str(target_lab[0]),
fontsize=8)
ax.legend()
ax.grid(alpha=0.2)

- The complete code can be found here (GitHub repository)
3 Special image drawing
- Draw a heat map through a matrix
plt.imshow(matrix)
plt.matshow(matrix)
Example: Drawing a fusion matrix heat map.
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict
y_train_pred = cross_val_predict(forest_clf, X_train_scaled, y_train, cv=5)
conf_mat = confusion_matrix(y_train ,y_train_pred)
norm_conf_mat = conf_mat / conf_mat.sum(axis=1, keepdims=True)
np.fill_diagonal(norm_conf_mat, 0)
plt.matshow(norm_conf_mat, cmap=plt.get_cmap('autumn_r'))
plt.xticks(range(len(norm_conf_mat)),np.arange(0,10,1),rotation=30)
plt.yticks(range(len(norm_conf_mat[0])),np.arange(0,10,1),rotation=30)
plt.xlabel("predict")
plt.ylabel('real')
for x_pos, val in enumerate(norm_conf_mat):
for y_pos , vals in enumerate(val):
plt.text(x_pos, y_pos, np.round(vals,5),
va='center',ha='center',fontsize=5)

- The complete data processing code can be found here (GitHub repository)
4. Image classification and coloring
- Grid x and y
xx,yy = np.meshgrid(x,y) - Classify coloring based on function values
ax,contourf(xx,yy,zz,cmap)
Example, Moon data classification.
from sklearn.tree import DecisionTreeClassifier
from matplotlib import pyplot as plt
# train one default CART with moon datasets
tree_clf2 = DecisionTreeClassifier(max_depth=10)
tree_clf2.fit(X,y)
x_axis = np.arange(-2,3,0.1)
y_axis = np.arange(-1,1.5,0.1)
xx, yy = np.meshgrid(x_axis,y_axis)
zz = np.zeros_like(xx)
for ly in range(len(x_axis)):
for lx in range(len(y_axis)):
zz[lx, ly] = tree_clf2.predict([[x_axis[ly],y_axis[lx]]])
fig,ax = plt.subplots(1,1,facecolor='whitesmoke',edgecolor='grey',
figsize=(4,3))
ax.contourf(xx,yy,zz,cmap=plt.cm.Spectral)
class_num = 2
marker_name = [4,"*"]
label_name = ['class0','class1']
color_name = ['darkblue','orange']
for index in range(class_num):
ax.scatter(X[np.where(y==index),0],X[np.where(y==index),1],
label=label_name[index],color=color_name[index],
marker=marker_name[index],lw=0.2)
ax.legend()
ax.grid(alpha=0.5)
