seaborn可视化学习之categorial visualization(附数据集)

Seaborn是一个做数据可视化效果很棒的库。在看了官方tutorial之后,尝试用Iris鸢尾花数据集实践一下categorical visualization,也就是数据按类别进行可视化。
首先介绍一下Iris鸢尾花数据集,内容摘自百度百科:Iris数据集是常用的分类实验数据集,由Fisher, 1936收集整理。“Iris也称鸢尾花卉数据集,是一类多重变量分析的数据集。数据集包含150个数据集,分为3类,每类50个数据,每个数据包含4个属性。可通过花萼长度,花萼宽度,花瓣长度,花瓣宽度4个属性预测鸢尾花卉属于(Setosa,Versicolour,Virginica)三个种类中的哪一类”。

导入库

In [1]:
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

读取数据

In [2]:
iris = pd.read_csv('../input/iris/iris.csv')
iris.head()
Out[2]:
 sepal_lengthsepal_widthpetal_lengthpetal_widthspecies
05.13.51.40.2setosa
14.93.01.40.2setosa
24.73.21.30.2setosa
34.63.11.50.2setosa
45.03.61.40.2setosa

数据字段介绍:

  • sepal_length:花萼长度,单位cm
  • sepal_width:花萼宽度,单位cm
  • petal_length:花瓣长度,单位cm
  • petal_width:花瓣宽度,单位cm
  • 种类:setosa(山鸢尾),versicolor(杂色鸢尾),virginica(弗吉尼亚鸢尾)

在做categorical visualization的时候,seaborn给出了基础的stripplot &swarmplotboxplot & violinplotbarplot & pointplot,以及抽象化的factorplot.下面就用纸鸢花数据集做一下讲解。

Stripplot

Stripplot的本质就是把数据集中具有quantitative属性的变量按照类别去做散点图(Scatterplot)。

我们将纸鸢花数据集中不同种类花的sepal length做stripplot可视化

In [3]:
plt.figure(1,figsize=(12,6))

plt.subplot(1,2,1)
sns.stripplot(x='species',y='sepal_length',data=iris) #stripplot
plt.title('Striplot of sepal length of Iris species')

with sns.axes_style("whitegrid"): # 这个是临时设置样式的命令,如果不写,则按默认格式'darkgrid'进行绘制
    plt.subplot(1,2,2)
    plt.title('Striplot of sepal length of Iris species')
    sns.stripplot(x='species',y='sepal_length',data=iris,jitter=True) # jitterplot

plt.show()

上边左侧的图片便是在默认风格下用stripplot绘制的散点图。在很多情况下,stripplot中的点会重叠,使得我们不容易看出点的分布情况。一个简单的解决办法就是用在stripplot的基础上绘制抖动图(jitterplot),仅沿着类别坐标轴的方向去随机微调整点的位置,显示出分布情况。

Swarmplot

另一个解决stripplot中点重叠的办法就是绘制swarmplot,它的本质就是用通过算法,在类别坐标轴的方向上去‘延展’绘制这些原本重合的点。 我们将纸鸢花数据集中不同种类花的petal length和petal width做swarmplot可视化。

In [4]:
plt.figure(1,figsize=(12,6))

plt.subplot(1,2,1)
sns.swarmplot(x='species',y='petal_length',data=iris) 

with sns.axes_style("ticks"): # 这次使用了ticks风格
    plt.subplot(1,2,2)
    sns.swarmplot(x='species',y='petal_width',data=iris)

plt.show()

Boxplot

箱形图,主要包含六个数据节点,将一组数据从大到小排列,分别计算出上边缘,上四分位数Q3,中位数,下四分位数Q1,下边缘,还有异常值。 下面将纸鸢花数据集中的四个变量sepal_length, sepal_width, petal_length和petal_width做箱形图可视化。

In [5]:
var = ['sepal_length','sepal_width','petal_length','petal_width']
axes_style = ['ticks','white','whitegrid', 'dark']

fig = plt.figure(1,figsize=(12,12))

for i in range(4):
    with sns.axes_style(axes_style[i]): # 将除了默认的darkgrid之外的样式都展现一遍
        plt.subplot(2,2,i+1)
        sns.boxplot(x='species',y=var[i],data=iris)

plt.show()

Violinplot

Violinplot相当于结合了箱形图与核密度图,更好地展现出数据的量化形态。展示如下:

In [6]:
context= ['notebook','paper','talk','poster']
axes_style = ['ticks','white','whitegrid', 'dark']

plt.figure(1,figsize=(12,12))
for i in range(4):
    with sns.axes_style(axes_style[i]):#设置axes_style
        sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster
        plt.subplot(2,2,i+1)
        plt.title(str(var[i])+ ' in Iris species')
        sns.violinplot(x='species',y=var[i],data=iris)

plt.show()

Violinplot用kernel density estimate去更好地描述了quantitative变量的分布。
与此同时,也可以组合swarmplot和boxplot或violinplot去描述quantitative变量。用鸢尾花数据集展示如下:

In [7]:
context= ['notebook','paper','talk','poster']
axes_style = ['ticks','white','whitegrid', 'dark']

plt.figure(1,figsize=(12,12))
for i in range(4):
    with sns.axes_style(axes_style[i]):#设置axes_style
        sns.set_context(context[i])#设置context
        plt.subplot(2,2,i+1)
        plt.title(str(var[i])+ ' in Iris species')
        sns.swarmplot(x='species', y=var[i], data=iris, color="w", alpha=.5) 
        sns.violinplot(x='species', y=var[i], data=iris, inner=None) if i%2 ==0 \
        else sns.boxplot(x='species', y=var[i], data=iris) # 分别用swarmplot+violinplot 和swarmplot + boxplot

plt.show()

Barplot

Barplot主要是展现在分类中的quantitative变量的平均值情况,并且用了boostrapping算法计算了估计值的置信区间和error bar.用鸢尾花数据集展示如下:

In [8]:
plt.figure(1,figsize=(12,12))
for i in range(4):
    with sns.axes_style(axes_style[i]):#设置axes_style
        sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster
        plt.subplot(2,2,i+1)
        plt.title(str(var[i])+ ' in Iris species')
        sns.barplot(x='species',y=var[i],data=iris)
plt.show()

Countplot

如果想知道在每个类别下面有多少个观察值,用countplot就可以,相当于是做一个observation counts,用鸢尾花数据集展示如下:

In [9]:
plt.figure(figsize=(5,5))
sns.countplot(y="species", data=iris) # 设置y='species',将countplot水平放置
plt.title('Iris species count')
plt.show()

Pointplot

Pointplot相当于是对barplot做了一个横向延伸,一方面,用point estimate和confidence level去展示barplot的内容;另一方面,当每一个主类别下面有更细分的sub-category的时候,pointplot可以便于观察不同sub-category在各主类别之间的联系。展示如下:

In [10]:
plt.figure(1,figsize=(12,12))
for i in range(4):
    with sns.axes_style(axes_style[i]):#设置axes_style
        sns.set_context(context[i]) # 设置context style,默认为notebook,除此之外还有paper,talk,poster
        plt.subplot(2,2,i+1)
        plt.title(str(var[i])+ ' in Iris species')
        sns.pointplot(x='species',y=var[i],data=iris)
plt.show()

Factorplot

Factorplot可以说是seaborn做category visualization的精髓,前面讲的这些plot都可以说是factorplot的具体展示。我们可以用PariGrid去实现对多个类别的数值特征用同一种plot做可视化。

In [11]:
sns.set(style="ticks")
g = sns.PairGrid(iris,
             x_vars = ['sepal_length','sepal_width','petal_length','petal_width'],
            y_vars = 'species',
            aspect=0.75,size=4) # 设置间距和图片大小
g.map(sns.violinplot,palette='pastel')
plt.show()

附上各plot function的API,今后将会对API中的参数结合tutorial讲讲,如何做出更好的可视化效果。更新ing

In [12]:
# seaborn.stripplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# jitter=False, dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', 
# linewidth=0, ax=None, **kwargs)
In [13]:
# seaborn.swarmplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# dodge=False, orient=None, color=None, palette=None, size=5, edgecolor='gray', linewidth=0, ax=None, **kwargs)
In [14]:
# seaborn.boxplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, fliersize=5, l
# inewidth=None, whis=1.5, notch=False, ax=None, **kwargs)
In [15]:
# seaborn.violinplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# bw='scott', cut=2, scale='area', scale_hue=True, gridsize=100, width=0.8, inner='box', 
# split=False, dodge=True, orient=None, linewidth=None, color=None, palette=None, 
# saturation=0.75, ax=None, **kwargs)
In [16]:
# seaborn.lvplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# orient=None, color=None, palette=None, saturation=0.75, width=0.8, dodge=True, 
# k_depth='proportion', linewidth=None, scale='exponential', outlier_prop=None, ax=None, **kwargs)
In [17]:
# seaborn.pointplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# estimator=<function mean>, ci=95, n_boot=1000, units=None, markers='o', linestyles='-', 
# dodge=False, join=True, scale=1, orient=None, color=None, palette=None, errwidth=None, capsize=None, ax=None, **kwargs)
In [18]:
# seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, 
# estimator=<function mean>, ci=95, n_boot=1000, units=None, orient=None, color=None, palette=None, 
# saturation=0.75, errcolor='.26', errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)

小结

seaborn是一个很棒的可视化库,尤其是当数据维度很大的时候,seaborn可以让我们用最少的代码去绘制一些描述性统计的图,便于找寻各维度变量之间的特征。此篇文档也是我对seaborn的学习笔记,这次整理的内容是关于category visualization。下次将会选取其他数据集去整理关于distribution visualization的内容。

附数据集:链接:https://pan.baidu.com/s/1jyMAmKPm583q81JnqIA9GA 密码:vqq6

Reference:

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值