python matplotlib绘图参数总结

0 概述

首先建立画布,建议使用fig, ax = plt.subplots(),将所有的绘制任务都分配到ax对象上进行。注意,除非使用1*1的画布分区,否则此时ax将会是一个二维数组,需要以数组的形式获取不同位置的ax对象

1 调整图像外部辅助线和图例的重要因素

  1. 主标题
    fig.suptitle("title")
  2. 副标题
    ax.set_title("title)
  3. 坐标轴标签
    ax.set_xlabel([array]) ax.set_ylabel([array])
  4. 坐标轴显示范围
    ax.set_xlim([lower, upper]) ax.set_ylim([lower, upper])
  5. 坐标轴位置
    ax.spines["left|top|right|bottom"].set_position(("data|outward,axes",value))
  6. 坐标轴显示
    ax.spines["left|top|right|bottom"].set_visible(True|False)
  7. 坐标轴颜色
    ax.spines["left|top|right|bottom"].set_color(“color”)
  8. 图例
    ax.legend(loc="upper right|upper left}bottom left| bottom right| left|right|top|bottom|best")
    该性质需要在各个图像曲线中定义label变量
  9. 网格
    ax.grid(alpha=0.5) alpha设置透明度
  10. log坐标显示
    ax.set_xscale('log')
    ax.set_yscale('log')

示例,sigmoid函数绘制

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()

#

2 调整图像内部图线的重要因素

  1. 绘制横纵辅助线
    ax.hlines(y,x_left,x_right, ls=':', color='gray')
    ax.vlines(x,y_bottom,y_up, ls=':', color='gray')
  2. 绘制横纵坐标轴
    ax.axhline(pos, color='grey', linewidth=1)
    ax.axvline(pos, color='grey', linewidth=1)
  3. 绘制不同曲线
    ax.polt()
    ax.scatter()
  4. 填充曲线中间位置
    ax.fill_between(x,y1,y2)
  5. 添加曲线注释
    plt.annotate(text ,xy,xytext,arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)
    xy表示箭头位置,xytext表示文字位置
    ax.text(s,x,y,fontsize,color)
    以上两个函数常与for循环一同使用

annotate 示例

x = np.linspace(0, 10, 30)
 
plt.plot(x, np.sin(x),c = '#0ffef9',label = 'sin(x)')
plt.annotate(text = '底点',xy = (4.65,-1),xytext = (4.2,0),
             arrowprops = {'headwidth':10,'facecolor':'r'},fontsize = 15)
plt.show()

在这里插入图片描述

示例, knn分组

from matplotlib import pyplot as plt
import matplotlib


plt.rcParams['font.sans-serif']=['SimHei'] #指定默认字体 SimHei为黑体
plt.rcParams['axes.unicode_minus']=False   #用来正常显示负号

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)

在这里插入图片描述

3 特殊图像绘制

  1. 通过矩阵绘制热力图
    plt.imshow(matrix)
    plt.matshow(matrix)

示例,confusion matrix热力图绘制

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)

在这里插入图片描述

4 图像分类涂色

  1. 将x,y网格化
    xx,yy = np.meshgrid(x,y)
  2. 根据函数值分类涂色
    ax,contourf(xx,yy,zz,cmap)

示例, moon数据分类

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)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值