python可视化工具——seaborn模块

发布时间 2023-04-10 18:22:03作者: 木田心

python可视化工具——seaborn模块

  • 散点图

    import pandas as pd
    df['Mes'] = pd.to_datetime(df.Mes) #将Mes列的类型转换为日期,防止画图时横坐标重叠
    sns.scatterplot(df['Mes'],df['data science'])
    
  • 在同一张图中添加两个以上变量的信息,用颜色、大小来表示变量的值

    sns.relplot(x='Mes', y='deep learning', hue='data science', size='machine learning', col='categorical', data=df)
    
  • 热图

    sns.heatmap(df.corr(), annot=True, fmt='.2f')
    
  • 配对图,显示所有变量之间的关系

    sns.pairplot(df)
    
  • 按类别做配对图

    sns.pairplot(df, hue='categorical')  #categorical是分类变量
    
  • 联合图

    sns.jointplot(x='data science', y='machine learning', data=df)  #散点图与直方图的联合图
    
  • 小提琴图

    sns.catplot(x='categorical', y='data science', kind='violin', data=df)
    

小提琴图的顺序可以由参数order指定;
参数linewidth设置线宽;
参数width设置小提琴的宽。

##设置网格线、背景色、边框线
plt.figure(figsize=(8,6), facecolor='white', edgecolor='black')
ax = sns.violinplot(x='categorical', y='data science', data=df)
ax.patch.set_facecolor('blue')
ax.patch.set_alpha(0.2)
ax.spines['right'].set_color('black')
ax.spines['left'].set_color('black')
ax.spines['top'].set_color('black')
ax.spines['bottom'].set_color('black')
plt.grid(False)
## 绘制小提琴图,并增加散点分布
ax = sns.violinplot(x='categorical', y='data science', data=df)
ax = sns.swarmplot(x='categorical', y='data science', data=df, color='gray')
  • 分组小提琴图

    df['day'] = df['Mes'].dt.day_name() #增加一列'day',表示星期几
    sns.catplot(x='day', y='data science', hue='categorical', kind='violin', data=df)
    

或者:

sns.violinplot(x='day', y='data science', hue='categorical', data=df, palette="Set2", split=True, scale="count", inner="box") #palette表示颜色,split表示是否把两类画到一起,inner="box"内部是箱线图
  • 箱线图

    sns.boxplot(),用法与小提琴图一样。
    参数notch可以指定是否有缺口,值为True时有缺口。

  • 创建多个图形

    import matplotlib.pyplot as plt
    plt.subplot(121)
    sns.scatterplot(x='Mes', y='deep learning', hue='categorical', data=df)
    plt.title('Deep learning')
    plt.subplot(122)
    sns.scatterplot(x='Mes',y='machine learning', hue='categorical', data=df)
    plt.title('Machine learning')
    

或者:

import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, sharey=True, figsize=(8,4))
sns.scatterplot(x='Mes', y='deep learning', hue='categorical', data=df, ax=axes[0])
axes[0].set_title('Deep learning')
sns.scatterplot(x='Mes',y='machine learning', hue='categorical', data=df, ax=axes[1])
axes[1].set_title('Machine learning')