Data Visualization with Seaborn 学习笔记


course:Data Visualization with Seaborn from DataCamp

FOUNDATION

import seaborn as sns

默认生成高斯核密度估计分布图 Gaussian Kernel Density Estimate(KDE),图像类似于直方图

sns.distplot(df[column])
plt.show()
image.png

若使用pandas默认的plot功能来绘制直方图的话,语句如下:

df[column].plot.hist()
plt.show()
image.png
可以关闭KDE拟合曲线,也可以设定bin的数量
sns.distplot(df[column], kde=False, bins=10 )
image.png

仅留下拟合曲线,关闭直方图, 同时将曲线下的面积加上阴影

sns.displot(df[column], hist=False, rug=True, kde_kws={'shade':True})
image.png

绘制散点回归图

sns.regplot(x=column1, y=column2, data=df)
image.png

regplot的更高级版本,lmplot

sns.lmplot(x=column1, y=column2, data=df)
image.png

lmpolt的更多用法

sns.lmpolt(x='insurance_losses', y='premiums', data=df, hue='Region')
plt.show()
image.png
sns.lmpolt(x='insurance_losses', y='premiums', data=df, col='Region')
plt.show()
image.png
sns.lmpolt(x='insurance_losses', y='premiums', data=df, row='Region')
plt.show()
image.png

seaborn有很多默认配置,可以通过sns.set()来调用。这些配置可以覆盖matplot和pandas的plot

sns.set()
df['Tuition'].plot.hist()
plt.show()
image.png
for style in ['white', 'dark', 'whitegrid', 'darkgrid','ticks']:
    sns.set_style(style)
    sns.distplot(df['Tuition'])
    plt.show()
image.png

可视化应该减少不必要的标记,让数据自己来说话。使用despine()方法来移除坐标轴,默认移除顶部和右侧坐标轴

sns.set_style('white')
sns.distplot(df['Tuition'])
sns.despine(left = True)
image.png

Customizing Seaborn Plots

seaborn支持使用matplot的color codes来给图像添加颜色。任意matplot的color codes都可以对应到seaborn的调色盘上

sns.set(color_codes=True)
sns.distplot(df['Tuition'], color='g']
image.png

seaborn使用set_palette()函数来定义一个调色盘。seaborn有六种默认的调色盘

for p in sns.palettes.SEABORN_PALETTES:
    sns.set_palette(p)
    sns.distplot(df['Tuition'])
image.png

显示调色盘:

sns.palplot()函数显示一个调色盘的实际效果
sns.color_palette()函数返回当前的调色盘

for p in sns.palettes.SEABORN_PALETTES:
    sns.set_palette(p)
    sns.palplot(sns.color_palette())
    plt.show()
image.png

有三种主要的调色盘类型:

Circular colors:用于无序的分类数据
sns.palplot(sns.color_palette("Paired', 12))

image.png

Sequential colors:用于数据存在一个从高到低的循序渐变时
sns.palplot(sns.color_palette("Blues", 12))

image.png

Diverging colors:用于关注数据的两个极端时
sns.palplot(sns.color_palette("BrBG", 12))

image.png

sns.palplot(sns.color_palette('coolwarm', 6))

image.png

sns.palplot(sns.color_palette('husl', 12))

image.png

seaborn使用matplot作为绘图的底层库。大部分时候你可以使用seaborn的API来完成可视化制定,但是有时也需要使用matplot进行客户化设定。

图层设定

fig, ax = plt.subplots()
sns.distplot(df['Tuition'], ax=ax)
ax.set(xlabel="Tuition 2013-14", ylabel="Distribution", xlim=(0,50000), 
          title="2013-14 Tuition and Fees Distribution")  #xlabel, ylabel, xlim(设置x轴范围), title
image.png

结合构建多张图

fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, sharey=True, figsize=(7,4)) #y轴共用
sns.distplot(df['Tuition'], ax=ax0)
sns.distplot(df.query('State=="MN" ')['Tuition'], ax=ax1) #DataFrame.query 对列进行条件查询
ax1.set(xlabel='Tuition (MN)', xlim=(0,70000))
ax1.axvline(x=20000, label='My Budget', linestyle='--')
ax1.legend()
image.png

Additional Plot Types

seaborn将数据分类图分成三组

第一组:包括散点图stripplot()swarmplot(),将每一个独立观察到的样本显示在图上

image.png

第二组:包括箱线图boxplot(),小提琴图violinplot()lvplot(),这些图对分类数据进行抽象表示

image.png

第三组:包括barplot()pointplot()countplot(),显示了对分类变量的统计估计。其中,barplot()pointplot()包含了有用的汇总信息,countplot()显示了实例的数量

image.png

散点图stripplot()显示了观察到的每一个数据,在有些情况下很难看到独立的数据点。使用jitter参数添加随机噪声,使数据分布更加明晰,避免样本堆叠。噪声只影响散点图,不影响回归

{x,y}_jitter : floats, optional
Add uniform random noise of this size to either the x or y variables. The noise is added to a copy of the data after fitting the regression, and only influences the look of the scatterplot. This can be helpful when plotting variables that take discrete values.

sns.stripplot(data = df, y='DRG Definition', x='Average Coverage Charges', jitter=True)
image.png

使用更高级的swarmplot()来展示所有的数据。该方法将所有点都分散开绘制,不会堆叠。该方法的缺点在于,当数据量太大时,这种方法无法很好的进行缩放

sns.swarmplot(data=df, y='DRG Definition', x='Average Coverage Charges')
image.png

箱线图boxplot()展示了几种关于数据分布的测量值,包括中位数,上下四分位数以及异常点。

sns.boxplot(data = df, y='DRG Definition', x='Average Coverage Charges')
image.png

小提琴图violinplot()结合了核密度图和箱线图,提供了另一种展示数据分布的视角。由于采用了核密度计算,所以小提琴图不会显示所有的数据点。该方法在展示大数据集时非常有效,但是绘图时需要集中算力。

sns.violinplot(data = df, y='DRG Definition', x='Average Coverage Charges')
image.png

信值图(letter value plot)lvplot(),是箱线图和提琴图的混合,但是对于大数据集有更强的缩放能力,渲染速度更快。

sns.lvplot(data = df, y='DRG Definition', x='Average Coverage Charges')
image.png

条形图barplot()显示了置信区间内的值的估计

sns.barplot(data = df, y='DRG Definition', x='Average Coverage Charges', hue='Region')
image.png

统计指标点图pointplot()类似于条形图,展示了一个总体上的衡量以及置信区间。可以用来观察不同分类值之间是怎样变化的

sns.pointplot(data = df, y='DRG Definition', x='Average Coverage Charges', hue='Region')
image.png

countplot()展示了每个变量的实例的个数。

sns.countplot(data = df, y='DRG Definition', hue='Region')
image.png

e.g.

加入调色盘功能

sns.lvplot(data=df, x='Award_Amount', y='Model Selected', palette='Paired', hue= 'Region')
plt.show()
image.png

使用capsize画出置信区间

sns.pointplot(data=df, y='Award_Amount', x='Model Selected', capsize=.1)
plt.show()
image.png

回归线

sns.regplot(data=df, x='temp', y='total_rentals', marker='+')
image.png

残差图(residualplot)residplot()用来衡量回归模型的适用性。残差值应该随机穿过水平线。在这个例子中,数据分布略带一点弧线,说明可能需要一个非线性模型来拟合

sns.residplot(data=df, x='temp', y='total_rentals')
image.png

多项式回归:seaborn将以numpy为底层函数来实现多项式拟合

sns.regplot(data=df, x='temp', y='total_rentals', order=2)
image.png

通过residplot()来分析二次曲线的拟合程度,可以看到,相对于一次曲线,二次曲线的的残差值分布更为均匀,所以使用二次曲线会是一个更好的选择

sns.residplot(data=df, x='temp', y='total_rentals', order=2)
image.png

分类数值的回归图

sns.regplot(data=df, x='mnth', y='total_rentals', x_jitter = .1, order=2)
image.png

有些情况下即使使用了jitter参数,也很难分辨出变量的变化趋势。使用x_estimator()有助于可视化分析

sns.regplot(data=df, x='mnth', y='total_rentals', x_estimator=np.mean, order=2)
image.png

对于连续变量,x_bins可以用来将变量拆成离散的bin,回归线依然可以拟合所有数据。这个方法比使用pandas或其他工具来拆分要快的多

sns.regplot(data=df, x='temp', y='total_rentals', x_bins=4)
image.png

不显示回归线的写法

sns.regplot(data=df, x='UG', y='Tuition', fig_reg = False)
image.png

热力图heatmap():热力图接受一个矩阵来完成制图

pandas中常用crosstab()函数来操作数据,使用aggfunc参数来求出月份和星期结合数据的平均值

pd.crosstab(df["mnth"], df["weekday"], values=df["total_rentals"], aggfunc='mean').round(0)
image.png
sns.heatmap(pd.crosstab(df["mnth"], df["weekday"],  values=df["total_rentals"], aggfunc='mean'))
image.png

定制热力图

sns.heatmap(df_crosstab, annot=True, fmt="d", cmap="YlGnBu", cbar=False, linewidths=.5)

annot=True:(annotate)在每个单元格内显示标注
fmt="d":确保显示结果是整数(格式化输出)
cmap="YIGnBu":设置填充颜色:黄色,绿色,蓝色
cbar=False:不显示color bar
linewidths=.5:在单元格之间加入小间隔,方便数据阅读

image.png

Centering the heatmap color scheme

sns.heatmap(df_crosstab, annot=True, fmt="d", cmap="YlGnBu", cbar=True,  center=df_crosstab.loc[9, 6])
image.png

热力图绘制相关性矩阵

pandas的corr()函数计算列与列之间的相关性,计算的结果可以用热力图来输出

sns.heatmap(df.corr())
image.png

Creating Plots on Data Aware Grids

Using FacetGrid, factorplot and lmplot

Seaborn's FacetGrid is the foundation for building data-aware grids. A data-aware grid allows you to create a series of small plots that can be useful for understanding complex data relationships.

seaborn绘制网格图要求数据“in tidy format”:每一行只有一个样本,变量包含在列里。

FacetGrid:方便用户掌握数据在行、列上的分布。使用FacetGrid()必须包含两步,定义FacetGridmap

When building a FacetGrid, there are two steps:
1.Create a FacetGrid object with columns, rows, or hue.
2.Map individual plots to the grid.

g=sns.FacetGrid(df, col="HIGHDEG")
g.map(sns.boxplot, 'Tuition', order=['1', '2', '3', '4'])
image.png

factorplot():实现FacetGrid的一种简单方式

sns.factorplot(x="Tuition", data=df, col="HIGHDEG", kind='box')

FacetGrid也可以用来绘制散点图和回归图

g=sns.FacetGrid(df, col="HIGHDEG")
g.map(plt.scatter, 'Tuition', 'SAT_AVG_ALL')
image.png

lmplot()类似于factorplot(),它提供了一种简单的方式在FacetGrid上绘制回归图和散点图。于factorplot()的区别在于lmplot默认绘制回归图

sns.lmplot(x="Tuition", data=df, y='SAT_AVG_ALL', col="HIGHDEG", fit_reg=False)

绘制经过数据筛选后的散点图,列为得分(HIGHDEG),行为地区(Region)

sns.lmplot(x="Tuition", data=df, y='SAT_AVG_ALL', col="HIGHDEG", row='Region')
image.png

e.g.

通过row_order参数来控制输出顺序

# Create FacetGrid with Degree_Type and specify the order of the rows using row_order
g2 = sns.FacetGrid(df, 
             row="Degree_Type",
             row_order=['Graduate', 'Bachelors', 'Associates', 'Certificate'])

# Map a pointplot of SAT_AVG_ALL onto the grid
g2.map(sns.pointplot, 'SAT_AVG_ALL')
image.png
#Create a factorplot() that contains a boxplot (box) of Tuition values varying by Degree_Type across rows.
sns.factorplot(data=df, x='Tuition', kind='box', row='Degree_Type')
image.png
# Create a facetted pointplot of Average SAT_AVG_ALL scores facetted by Degree Type 
sns.factorplot(data=df, x='SAT_AVG_ALL', kind='point', 
row='Degree_Type', row_order=['Graduate', 'Bachelors', 'Associates', 'Certificate'])
image.png
# Create an lmplot that has a column for Ownership, a row for Degree_Type and hue based on the WOMENONLY column
sns.lmplot(data=df, x='SAT_AVG_ALL', y='Tuition', col="Ownership", row='Degree_Type',
        row_order=['Graduate', 'Bachelors'], hue='WOMENONLY', col_order=inst_ord)
image.png

Using PairGrid and pairplot

PairGrid and pairplotFacetGrid类似,区别在于,使用PairGrid and pairplot时我们只选择关心的列进行作图

PairGrid shows pairwise relationships between data elements

image.png

使用PairGrid时我们不再定义行和列参数,而是使用变量参数vars

g = sns.PairGrid(df, vars=["Fair_Mrkt_Rent", "Median_Income"])
g = g.map(plt.scatter)
image.png

定制PairGrid的对角线图像

g=sns.PairGrid(df,vars=["Fair_Mrkt_Rent", "Median_Income"])
g=g.map_diag(plt.hist)  #主对角线,左上右下
g=g.map_offdiag(plt.scatter)  #非主对角线,右上左下
image.png

pairplot()

sns.pairplot(df, vars=["Fair_Mrkt_Rent", "Median_Income"], kind='reg', diag_kind='hist')
image.png

e.g.

sns.pairplot(df.query('BEDRMS < 3'), #选择卧室数量在3个以下的数据
             vars=["Fair_Mrkt_Rent", "Median_Income", "UTILITY"],
             hue='BEDRMS', palette='husl', plot_kws={'alpha': 0.5}) 

plot_kws={'alpha':0.5}修改了散点图的透明度,方便数据阅读

image.png

e.g.

sns.pairplot(data=df,vars=["fatal_collisions", "premiums"], kind='scatter', 
hue='Region', palette='RdBu',  diag_kws={'alpha':.5})
image.png

One area of customization that is useful is to explicitly define the x_vars and y_vars that you wish to examine. Instead of examining all pairwise relationships, this capability allows you to look only at the specific interactions that may be of interest.

# Build a pairplot with different x and y variables
sns.pairplot(data=df,
        x_vars=["fatal_collisions_speeding", "fatal_collisions_alc"],
        y_vars=['premiums', 'insurance_losses'],
        kind='scatter',
        hue='Region',
        palette='husl')
image.png
# plot relationships between insurance_losses and premiums
sns.pairplot(data=df,
             vars=["insurance_losses", "premiums"],
             kind='reg',
             palette='BrBG',
             diag_kind = 'kde',
             hue='Region')
image.png

Using JointGrid and jointplot

JointGrid反应了两个变量分布之间的关系

image.png
g = sns.JointGrid(data=df, x="Tuition", y="ADM_RATE_ALL") 
g.plot(sns.regplot, sns.distplot)
image.png
g=sns.JointGrid(data=df,x="Tuition", y="ADM_RATE_ALL")
g=g.plot_joint(sns.kdeplot) #中间的kde图
g=g.plot_marginals(sns.kdeplot, shade=True) #边缘的kde图
g=g.annotate(stats.pearson) #标注变量之间的相关关系
image.png

jointplot()使用更简单,但是只提供较少的定制功能。seaborn自动包含了皮尔逊相关系数标注在图中

sns.jointplot(data=df, x="Tuition", y="ADM_RATE_ALL", kind='hex')
image.png

jointplot()提供简单的绘制scatter, hex, residual, regression and kde图像的功能

g=sns.jointplot(x="Tuition", y="ADM_RATE_ALL", kind='scatter', xlim=(0,25000), 
marginal_kws=dict(bins=15, rug=True), data=df.query('UG < 2500 & Ownership == "Public"'))
.plot_joint(sns.kdeplot))  kde图和散点图的叠加
image.png

Selecting Seaborn Plots

Univariate Distribution Analysis

1.distplot() is the best place to start for this analysis
2.rugplot() and kdeplot() can be useful alternatives

image.png

Regression Analysis

lmplot() performs regression analysis and supports facetting

image.png

Categorical Plots

Explore data with the categorical plots and facet with factorplot

image.png

pairplot and jointplot

1.Perform regression analysis with lmplot
2.Analyze distributions with distplot

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,711评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,932评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,770评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,799评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,697评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,069评论 1 276
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,535评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,200评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,353评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,290评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,331评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,020评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,610评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,694评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,927评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,330评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,904评论 2 341

推荐阅读更多精彩内容