python图表绘制 | seaborn入门(一):distplot与kdeplot

Seaborn介绍

官方链接:Seaborn: statistical data visualization

Seaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。

Seaborn其实是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn就能做出很具有吸引力的图,而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充,而不是替代物。同时它能高度兼容numpypandas数据结构以及scipystatsmodels等统计模式。掌握seaborn能很大程度帮助我们更高效的观察数据与图表,并且更加深入了解它们。

<img src="https://pic4.zhimg.com/v2-14b93a648dc3f3eb9890e586104299ca_b.jpg" data-rawwidth="547" data-rawheight="620" class="origin_image zh-lightbox-thumb" width="547" data-original="https://pic4.zhimg.com/v2-14b93a648dc3f3eb9890e586104299ca_r.jpg">

 

其有如下特点:

  • 基于matplotlib aesthetics绘图风格,增加了一些绘图模式
  • 增加调色板功能,利用色彩丰富的图像揭示您数据中的模式
  • 运用数据子集绘制与比较单变量和双变量分布的功能
  • 运用聚类算法可视化矩阵数据
  • 灵活运用处理时间序列数据
  • 利用网格建立复杂图像集

 

安装seaborn

  1. 利用pip安装
pip install seaborn

2. 在Anaconda环境下,打开prompt

conda install seaborn

 

distplot

seaborn.distplot - seaborn 0.7.1 documentation

seaborn的displot()集合了matplotlib的hist()与核函数估计kdeplot的功能,增加了rugplot分布观测条显示与利用scipy库fit拟合参数分布的新颖用途。具体用法如下:

seaborn.distplot(a, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None)

Parameters:

a : Series, 1d-array, or list.

Observed data. If this is a Series object with a name attribute, the name will be used to label the data axis.

bins : argument for matplotlib hist(), or None, optional #设置矩形图数量

Specification of hist bins, or None to use Freedman-Diaconis rule.

hist : bool, optional #控制是否显示条形图

Whether to plot a (normed) histogram.

kde : bool, optional #控制是否显示核密度估计图

Whether to plot a gaussian kernel density estimate.

rug : bool, optional #控制是否显示观测的小细条(边际毛毯)

Whether to draw a rugplot on the support axis.

fit : random variable object, optional #控制拟合的参数分布图形

An object with fit method, returning a tuple that can be passed to a pdf method a positional arguments following an grid of values to evaluate the pdf on.

{hist, kde, rug, fit}_kws : dictionaries, optional

Keyword arguments for underlying plotting functions.

vertical : bool, optional #显示正交控制

If True, oberved values are on y-axis.


 

Histograms直方图

 

直方图(Histogram)又称质量分布图。是一种统计报告图,由一系列高度不等的纵向条纹或线段表示数据分布的情况。 一般用横轴表示数据类型,纵轴表示分布情况。

%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import matplotlib.pyplot as plt #导入

import seaborn as sns
sns.set(color_codes=True)#导入seaborn包设定颜色

np.random.seed(sum(map(ord, "distributions")))
x = np.random.normal(size=100)
sns.distplot(x, kde=False, rug=True);#kde=False关闭核密度分布,rug表示在x轴上每个观测上生成的小细条(边际毛毯)

 

<img src="https://pic1.zhimg.com/v2-2430e4d758149fea821ac8b90d0418f0_b.jpg" data-rawwidth="490" data-rawheight="345" class="origin_image zh-lightbox-thumb" width="490" data-original="https://pic1.zhimg.com/v2-2430e4d758149fea821ac8b90d0418f0_r.jpg">

当绘制直方图时,你最需要确定的参数是矩形条的数目以及如何放置它们。利用bins可以方便设置矩形条的数量。如下所示:

 

sns.distplot(x, bins=20, kde=False, rug=True);#设置了20个矩形条

<img src="https://pic1.zhimg.com/v2-a614ae5a423003aacf841f5667060f2f_b.jpg" data-rawwidth="486" data-rawheight="339" class="origin_image zh-lightbox-thumb" width="486" data-original="https://pic1.zhimg.com/v2-a614ae5a423003aacf841f5667060f2f_r.jpg">

 

Kernel density estimaton核密度估计

核密度估计是在概率论中用来估计未知的密度函数,属于非参数检验方法之一。.由于核密度估计方法不利用有关数据分布的先验知识,对数据分布不附加任何假定,是一种从数据样本本身出发研究数据分布特征的方法,因而,在统计学理论和应用领域均受到高度的重视。

seaborn.kdeplot - seaborn 0.7.1 documentation

distplot()

sns.distplot(x, hist=False, rug=True);#关闭直方图,开启rug细条

<img src="https://pic3.zhimg.com/v2-d94f70553e2e050fb357f505962af185_b.jpg" data-rawwidth="501" data-rawheight="344" class="origin_image zh-lightbox-thumb" width="501" data-original="https://pic3.zhimg.com/v2-d94f70553e2e050fb357f505962af185_r.jpg">

kdeplot()

sns.kdeplot(x, shade=True);#shade控制阴影

<img src="https://pic2.zhimg.com/v2-2493da4bec720014af0e55b4bbe0be27_b.jpg" data-rawwidth="498" data-rawheight="343" class="origin_image zh-lightbox-thumb" width="498" data-original="https://pic2.zhimg.com/v2-2493da4bec720014af0e55b4bbe0be27_r.jpg">

 

Fitting parametric distributions拟合参数分布

可以利用distplot() 把数据拟合成参数分布的图形并且观察它们之间的差距,再运用fit来进行参数控制。

x = np.random.gamma(6, size=200)#生成gamma分布的数据
sns.distplot(x, kde=False, fit=stats.gamma);#fit拟合

<img src="https://pic3.zhimg.com/v2-1f0e2011d0aa1e10f8b74e0e4761abb9_b.jpg" data-rawwidth="502" data-rawheight="347" class="origin_image zh-lightbox-thumb" width="502" data-original="https://pic3.zhimg.com/v2-1f0e2011d0aa1e10f8b74e0e4761abb9_r.jpg">

 

Example Ⅰ for practice

<img src="https://pic2.zhimg.com/v2-a07d9732b5bbd373fc508075566125b6_b.jpg" data-rawwidth="536" data-rawheight="525" class="origin_image zh-lightbox-thumb" width="536" data-original="https://pic2.zhimg.com/v2-a07d9732b5bbd373fc508075566125b6_r.jpg">

Python source code:[download source: distplot_options.py]

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set(style="white", palette="muted", color_codes=True)
rs = np.random.RandomState(10)

# Set up the matplotlib figure
f, axes = plt.subplots(2, 2, figsize=(7, 7), sharex=True)
sns.despine(left=True)

# Generate a random univariate dataset
d = rs.normal(size=100)

# Plot a simple histogram with binsize determined automatically
sns.distplot(d, kde=False, color="b", ax=axes[0, 0])

# Plot a kernel density estimate and rug plot
sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0, 1])

# Plot a filled kernel density estimate
sns.distplot(d, hist=False, color="g", kde_kws={"shade": True}, ax=axes[1, 0])

# Plot a historgram and kernel density estimate
sns.distplot(d, color="m", ax=axes[1, 1])

plt.setp(axes, yticks=[])
plt.tight_layout()

 

Example Ⅱ for practice

利用kdeplot探索某大学学生消费习惯于助学金获得关系,数据集如下所示:

<img src="https://pic3.zhimg.com/v2-e2fcda273f3518f42e4afb19b3ee9bc8_b.jpg" data-rawwidth="300" data-rawheight="350" class="content_image" width="300">

 

一共有10798条数据

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set(style="white", palette="muted", color_codes=True)

train = pd.read_csv('train.csv')#导入数据集
#ax1表示对获得助学金的人分布作图,ax2表示对未获得助学金的人分布作图
ax1=sns.kdeplot(train['金额'][train['是否得到助学金']==1],color='r')
ax2=sns.kdeplot(train['金额'][train['是否得到助学金']==0],color='b')

 

<img src="https://pic3.zhimg.com/v2-657933daf5007c2f938d12c45113f028_b.jpg" data-rawwidth="533" data-rawheight="358" class="origin_image zh-lightbox-thumb" width="533" data-original="https://pic3.zhimg.com/v2-657933daf5007c2f938d12c45113f028_r.jpg">

通过分布可以发现,蓝色图像分布靠右,红色分布靠左,x轴表示消费金额,得出得到助学金的同学日常消费较未得到的同学更低,印证了助学金一定程度用来帮助贫困生改善生活的应用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值