seaborn可视化绘图工具使用手册

seaborn使用版本:0.11.1
本文介绍了seaborn的使用接口,以及常用的长款表转换方法

import seaborn as sns
sns.__version__
'0.11.1'
import matplotlib.pyplot as plt 
import pandas as pd 
import numpy as np 

Seaborn的使用结构

  • seaborn的借口都是扁平的,都通过seaborn.xx()调用
  • 但是借口之间有上下级关系,存在着彼此调用
  • seaborn的绘图函数主要分类三类,如下所示
    image.png
  • 在每个类别中,都存在两种函数
    1. 基于坐标轴的,axes-level,简单理解就是绘制单图的函数
      • 绘图对象是plt中的Axes
    2. 基于图的,Figure-level,简单理解就是绘制多图的函数,通过调用单图实现
      • 绘图对象是FacetGrid
      • 对应上图中的三个顶类函数relplot,displot,catplot

Figure-Level 绘图 displot

  • 调用数据集出现URL故障时,请参考:链接
penguin = sns.load_dataset('penguins',cache=True,data_home='../../seaborn-data')
penguin.head()
speciesislandbill_length_mmbill_depth_mmflipper_length_mmbody_mass_gsex
0AdelieTorgersen39.118.7181.03750.0Male
1AdelieTorgersen39.517.4186.03800.0Female
2AdelieTorgersen40.318.0195.03250.0Female
3AdelieTorgersenNaNNaNNaNNaNNaN
4AdelieTorgersen36.719.3193.03450.0Female
  • displot是Figure级别的绘图函数,通过kind可以调用低级的hist,kde等绘图函数
  • 注意与axe级别绘图不同,它的legend在图外边
sns.displot(data = penguin,x = 'flipper_length_mm',hue ='species',kind='kde')
<seaborn.axisgrid.FacetGrid at 0x28ab787fca0>

png

  • 通过g.ax可以获得Figure-level对象的坐标轴,并添加其他子图
tips = sns.load_dataset("tips",cache=True,data_home='../../seaborn-data/')
g = sns.relplot(data=tips, x="total_bill", y="tip")
g.ax.axhline(y = 5)
<matplotlib.lines.Line2D at 0x28abd00df10>

png

  • 修改图的属性
  • Figure类型的图能智能将标签应用在子图上
g = sns.relplot(data=penguin, x="flipper_length_mm", y="bill_length_mm", col="sex")
g.set_axis_labels("Flipper length (mm)", "Bill length (mm)")
<seaborn.axisgrid.FacetGrid at 0x28abd0d87c0>

png

  • 使用col,row等参数,可以绘制多个子图
  • 在参数中,可以直接加入axe函数的参数,比如bins
sns.displot(data = penguin,x = 'flipper_length_mm',hue ='species',col='species',cumulative = True,bins = 10)
<seaborn.axisgrid.FacetGrid at 0x28ab74cd790>

png

  • 通过height,aspect可以控制子图的大小和形状
  • width=height*aspect
  • 默认情况下,每个子图都是正方形
sns.displot(data = penguin,x = 'flipper_length_mm',hue ='species',col='species'
            ,cumulative = True,bins = 10,col_wrap=1,height=4,aspect=1.2)
<seaborn.axisgrid.FacetGrid at 0x28ab9ff2820>

png

Axe-Level绘图 histplot直方图

  • 默认会自动通过plt.gca获得当前正在绘制的axe
sns.histplot(data = penguin,x = 'flipper_length_mm',hue ='species',multiple='stack')
<matplotlib.axes._subplots.AxesSubplot at 0x28ab704ea30>

png

  • 可以指定ax = xx来指定绘制到那个坐标轴上
f,[ax1,ax2] = plt.subplots(1,2,figsize = (8,4))
sns.scatterplot(data=penguin, x="flipper_length_mm", y="bill_length_mm", hue="species",ax = ax1)
sns.histplot(data=penguin, x="species", hue="species", shrink=.8, alpha=.8, legend=False, ax=ax2)
<matplotlib.axes._subplots.AxesSubplot at 0x28aba4c55e0>

png

  • kde分布拟合图
sns.kdeplot(data = penguin,x = 'flipper_length_mm',hue ='species')
<matplotlib.axes._subplots.AxesSubplot at 0x28ab6ac77c0>

png

在同一张图上绘制多个视图

joinplot

  • 在坐标轴上绘制变量的一维分布
sns.jointplot(data=penguin,x = 'flipper_length_mm',y = 'bill_length_mm',
             hue = 'species')
<seaborn.axisgrid.JointGrid at 0x28ab705ce20>

png

pairplot()

  • 会将所有数值型的列作为变量,两两组合绘制子图
sns.pairplot(data=penguin,hue='species')
<seaborn.axisgrid.PairGrid at 0x28abc62d520>

png

seaborn接受的数据类型

长表long-table

  • 每一列都是一个变量
  • 每一行是一个样本(观察值)
flight = sns.load_dataset('flights',cache=True,data_home='../../seaborn-data/')
flight.head()
yearmonthpassengers
01949Jan112
11949Feb118
21949Mar132
31949Apr129
41949May121
  • 通过指定数据源,x,y的列名来绘制图
  • style来指定线型
sns.relplot(data=flight,x='year',y = 'passengers',hue='month',kind='line',style='month')
<seaborn.axisgrid.FacetGrid at 0x23dbd6a18b0>

png

宽表wide-table

  • 每一个行列交汇的点是一个样本点,而变量则是index和columns
  • seaborn不支持多级索引
flight_wide = flight.pivot(index='year',columns='month',values='passengers')
flight_wide.head()
monthJanFebMarAprMayJunJulAugSepOctNovDec
year
1949112118132129121135148148136119104118
1950115126141135125149170170158133114140
1951145150178163172178199199184162146166
1952171180193181183218230242209191172194
1953196196236235229243264272237211180201
  • 宽表绘图时,会自动将index和columns当做x,y
  • 注意线性会不同
sns.relplot(data=flight_wide,kind='line')
<seaborn.axisgrid.FacetGrid at 0x23dbd7632b0>

png

  • 在使用宽表时,有时候变量会不可预测
  • 比如当绘制单变量的图时,你不能确定index和columns哪一个被分配给x
sns.catplot(data=flight_wide, kind="box")
<seaborn.axisgrid.FacetGrid at 0x23dbe14b760>

png

脏数据

  • 既不是宽表也不是长表
anagrams = sns.load_dataset("anagrams",cache=True,data_home='../../seaborn-data/')
anagrams
subidrattnrnum1num2num3
01divided24.07
12divided34.05
23divided35.06
34divided57.05
45divided45.08
56divided55.06
67divided54.56
78divided57.08
89divided23.07
910divided65.06
1011focused65.06
1112focused89.08
1213focused65.09
1314focused88.07
1415focused88.07
1516focused68.07
1617focused77.06
1718focused78.06
1819focused56.06
1920focused66.05
  • 绘图时要先将原表转换为宽表或者长表
ana_long = anagrams.melt(id_vars=["subidr", "attnr"],var_name="solutions", value_name="score")
ana_long.head()
subidrattnrsolutionsscore
01dividednum12.0
12dividednum13.0
23dividednum13.0
34dividednum15.0
45dividednum14.0
sns.catplot(data=ana_long, x="solutions", y="score", hue="attnr", kind="point")
<seaborn.axisgrid.FacetGrid at 0x23dbce31580>

png

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 目录 1. 目录 2 2. 绘图函数Plotting functions 4 2.1. 可视化的统计关系Visualizing statistical relationships 4 2.1.1. 用散点图联系变量Relating variables with scatter plots 4 2.1.2. 强调线条图的连续性Emphasizing continuity with line plots 10 2.1.3. 显示与切面的多个关系Showing multiple relationships with facets 21 2.2. 分类数据绘图Plotting with categorical data 24 2.2.1. 分类散点图Categorical scatterplots 26 2.2.2. 分类观测值分布Distributions of observations within categories 31 2.2.3. 分类统计估计Statistical estimation within categories 37 2.2.4. 对“wide-form”数据作图Plotting “wide-form” data 41 2.2.5. 显示与facet的多个关系Showing multiple relationships with facets 43 2.3. 可视化数据集的分布Visualizing the distribution of a dataset 44 2.3.1. 绘制单变量分布Plotting univariate distributions 45 2.3.2. 绘制二元分布Plotting bivariate distributions 51 2.3.3. 在数据集中可视化成对关系Visualizing pairwise relationships in a dataset 55 2.4. 可视化线性关系Visualizing linear relationships 57 2.4.1. 函数绘制线性模型Functions to draw linear regression models 58 2.4.2. 拟合不同种类的模型Fitting different kinds of models 61 2.4.3. 在其他变量上的情况Conditioning on other variables 68 2.4.4. 控制图表的大小和形状Controlling the size and shape of the plot 71 2.4.5. 在其他上下文中绘制回归图Plotting a regression in other contexts 73 3. 多图网格Multi-plot grids 76 3.1. 构建结构化的多图网格Building structured multi-plot grids 76 3.2. 有条件的小倍数Conditional small multiples 77 3.3. 使用定制函数Using custom functions 86 3.4. 绘制成对的数据关系Plotting pairwise data relationships 90 4. 绘图美学Plot aesthetics 99 4.1. 控制图表美学Controlling figure aesthetics 99 4.1.1. Seaborn图表风格Seaborn figure styles 101 4.1.2. 删除轴上的小凸起Removing axes spines 104 4.1.3. 临时设置图表样式Temporarily setting figure style 105 4.1.4. 覆盖Seaborn样式的元素Overriding elements of the seaborn styles 106 4.1.5. 缩放图表元素Scaling plot elements 108 4.2. 选择调色板Choosing color palettes 111 4.2.1. 创建颜色调色板Building color palettes 111 4.2.2. 定性调色板Qualitative color palettes 112 4.2.3. 连续调色板Sequential color palettes 116 4.2.4. 不同颜色的调色板Diverging color palettes 122 4.2.5. 设置默认调色板Setting the default color palette 124 5. 教程中的数据集 125
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值