一、导入相关包
%config IPCompleter.greedy=True
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
二、Seaborn绘图风格设置
1.sns.set()设置风格
seaborn.set()函数参数:seaborn.set(context=‘notebook’, style=‘darkgrid’, palette=‘deep’, font=‘sans-serif’, font_scale=1, color_codes=True, rc=None)
从这个set()函数,可以看出,通过它我们可以设置背景色、风格、字型、字体等。我们定义一个函数,这个函数主要是生成100个0到15的变量,然后用这个变量画出6条曲线。
def sinplot(flip=2):
x = np.linspace(0, 15, 100)
for i in range(1, 6):
plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)
sns.set()
sinplot()
那么,问题来了,有人会说,这个set()函数这么多参数,只要改变其中任意一个参数的值,绘图效果就会发生变化,那我们怎么知道哪种搭配是最佳效果呢,难道我们要一个个去测试吗?当然不是,seaborn提供了5种默认的风格,我们在实际绘图中只要选择一种喜欢的风格就可以了,下面我们就看看这5种风格的用法及效果。
seaborn.set()使用5种默认风格
函数参数:seaborn.set_style(style=None, rc=None),这里style可选参数值有:darkgrid,whitegrid,dark,white,ticks,下面我们就通过设置不同的风格,看看每种风格的效果。
1)‘white’
sns.set(style='white')
sinplot()
2)‘whitegrid’
sns.set(style='whitegrid')
sinplot()
3)‘darkgrid’
sns.set(style='darkgrid')
sinplot()
4)‘dark’
sns.set(style='dark')
sinplot()
5)‘ticks’
sns.set(style='ticks')
sinplot()
2.seaborn.despine()
这个函数可以移除图像的上部和右侧的坐标轴,我们看看效果。
sinplot()
sns.despine()
这里默认移除了上部和右侧的轴,当然我们也可以移除其他轴,只要将表示四个边的参数值改为true即可,下面是个这个函数的参数seaborn.despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False),其中offset表示偏离左侧轴的距离。
sinplot()
sns.despine(offset=50)
3. 使用with打开某种风格
在matplotlib中我们已经学过了,在一个figure对象中,我们可以添加多个子图,那么如果不同的子图使用不同的风格,我们该如何做呢?很简单,使用with 打开某种风格,然后在with下画的图都使用with打开的分格,我们来看看代码。
fig = plt.figure()
with sns.axes_style("darkgrid"):
ax1 = fig.add_subplot(211)
sinplot(4)
fig.add_subplot(212)
sinplot(-4)
4. seaborn.set_context()
seaborn.set_context(context=None, font_scale=1, rc=None)这个函数也是来设置绘图背景参数的,它主要来影响标签、线条和其他元素的效果,但不会影响整体的风格,跟style有点区别。这个函数默认使用notebook,其他context可选值有:paper, talk, poster。下面我们看看具体的效果。
sns.set_context("paper")
plt.figure(figsize=(6, 4))
sinplot()
sns.set_context("talk")
plt.figure(figsize=(6, 4))
sinplot()
sns.set_context("poster")
plt.figure(figsize=(6, 4))
sinplot()
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
plt.figure(figsize=(6, 4))
sinplot()
5. 修改字体
sns.set(style="ticks", font='cmr10')
plt.xlabel('font cmr10')
plt.ylabel('this is a special font')
Text(0, 0.5, 'this is a special font')
sns.set(style="ticks", font='cmmi10')
plt.xlabel('font cmr10')
plt.ylabel('this is a special font')
Text(0, 0.5, 'this is a special font')
三、Seaborn.catplot()分类型数据绘图
下面所有函数的最高级别的整合接口:catplot()
Categorical scatterplots:
- stripplot() (with kind=“strip”; the default)
- swarmplot() (with kind=“swarm”)
Categorical distribution plots:
- boxplot() (with kind=“box”)
- violinplot() (with kind=“violin”)
- boxenplot() (with kind=“boxen”)
Categorical estimate plots:
- pointplot() (with kind=“point”)
- barplot() (with kind=“bar”)
- countplot() (with kind=“count”)
1. 分类散点图
分类坐标轴:catplot(kind=“strip”)默认
tips= sns.load_dataset("tips")
print(tips.head())
print(tips.dtypes)
total_bill tip sex smoker day time size
0 16.99 1.01 Female No Sun Dinner 2
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
total_bill float64
tip float64
sex category
smoker category
day category
time category
size int64
dtype: object
当在同一个类别中出现大量取值相同或接近的观测数据时,他们会挤到一起。seaborn中有两种分类散点图,分别以不同的方式处理了这个问题。 catplot()使用的默认方式是stripplot(),它给这些散点增加了一些随机的偏移量,更容易观察:
sns.catplot(x="day", y="total_bill", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c9aff28>
jitter参数控制着偏移量的大小,或者我们可以直接禁止他们偏移:
sns.catplot(x="day", y="tip", jitter=False,data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c8355c0>
蜂群图:catplot(kind=“swarm”)
相当于swarmplot() 避免了散点之间的重合,提供更好的方式来呈现观测点的分布。 但仅适用于较小的数据集。
sns.catplot(kind="swarm", x="day", y="tip", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c7f6160>
- hue参数:利用不同颜色区分
与关系图类似,也可以通过hue来增加一个维度。BUT分类图不支持size和style
sns.catplot(kind="swarm", x="day", y="tip", hue="sex", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c816208>
- col参数, 指定某一切面来考察数据
sns.catplot(kind="swarm", x="day", y="tip", hue="sex", col="smoker", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84cee2cc0>
- 考察切面时, 利用height, aspect参数
sns.catplot(x="day", y="tip", hue="sex", col="smoker", height=5, aspect=.8, data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd847b49fd0>
- 切面时, 使用参数 col_wrap, 让每行显示指定数量的图,如果超过该数量,则多行显示。
sns.catplot(x="day", y="tip", hue="sex", col="size", height=5, aspect=.8, col_wrap=2, data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd847cb1630>
- 关于x(分类型数据)轴的分类值的顺序,函数会自己推断。 如果数据是pandas的Categorical类型,那么默认的分类顺序可以在pandas中设置; 如果数据看起来是数值型的(比如1,2,3…),那他们也会被排序。 即使我们使用数字作为不同分类的标签,它们仍然是被当做分类型数据按顺序绘制在分类变量对应的坐标轴上的:
注意,2和4之间的距离与1和2之间的距离是一样的,它们是不同的分类,只会排序,但是并不会改变它们在坐标轴上的距离
sns.catplot(x="size", y="tip", kind="swarm", data=tips.query("size!=3"))
<seaborn.axisgrid.FacetGrid at 0x7fd84c735710>
- order参数:指定分类值顺序
sns.catplot(kind="swarm",x="size", y="tip", order=[6,5,4,3,2,1],data=tips.query("size!=3"))
<seaborn.axisgrid.FacetGrid at 0x7fd84c757278>
sns.catplot(kind="swarm", x="smoker",y="tip", order=["No","Yes"], data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c91efd0>
- 有些时候把分类变量放在垂直坐标轴上会更有帮助(尤其是当分类名称较长或者分类较多时)
只需要交换x和y分配的变量即可:
sns.catplot(x="total_bill", y="day", hue="time", kind="swarm", data=tips);
2、分类分布图
当数据量越来越大时,散点图在表现不同分类的观测值的分布信息就越来越捉襟见肘了。 此时,有其他的方式:
- 箱线图:catplot(kind=“box”)
- 小提琴图:catplot(kind=“violin”)
箱线图:catplot(kind=“box”)
展现了:离群点、上界、上四分位数、均值、中位数、下四分位数、下界、离群点
sns.catplot(kind="box", x="day", y="total_bill", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c842240>
增加一个维度的信息:
sns.catplot(kind="box", x="day", y="total_bill", hue="smoker", data=tips)#增加一个维度的信息
<seaborn.axisgrid.FacetGrid at 0x7fd889643b38>
上面的图中,默认了hue参数对应的变量smoker与坐标轴上的分类变量day是相互嵌套的(如,周四吸烟、周四不吸烟),这种操作叫**“dodging”**。 如果不是这种情形,应该禁用dodging,看下面的例子: hue的Weekend和day不是相互嵌套的:
× 错误的图:
tips["Weekend"]= tips["day"].isin(["Sat","Sun"]) # isin 返回布尔值
sns.catplot(kind="box", x="day", y="total_bill", hue="Weekend", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84cb5ef98>
√ 正确的图(禁用dodge,dodge=False):
sns.catplot(kind="box", x="day", y="total_bill", hue="Weekend",dodge=False, data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84f3754e0>
box的进阶:catplot(kind=“boxen”)
与箱线图相似但是能展示更多关于数据分布形状的信息,它对大数据更加友好:
sns.catplot(kind="boxen", x="day", y="total_bill", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84ceff358>
小提琴图:catplot(kind=“violin”)
- 它将箱线图和核密度估计(kde: kernel density estimation)结合起来
sns.catplot(kind="violin", y="day", x="total_bill",hue="time", data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84cc2bda0>
- 参数split=Ture
当一个额外的分类变量仅有2个水平时,我们也可以将它赋给hue参数,并且设置split=True,这样我们可以更加充分地利用空间来表达更多信息:
sns.catplot(kind="violin", y="day", x="total_bill",hue="time",split=True, data=tips)
<seaborn.axisgrid.FacetGrid at 0x7fd84c6a5048>
3. 分类统计估计图
在某些应用场景中,相对于展示每类的分布情况,更像展示每类的数据的集中趋势估计(统计量,如均值、中位数、方差等)。 有以下方式:
- 条形图:catplot(kind=“bar”)
- 直方图:catplot(kind=“count”)
- 点图:catplot(kind=“point”)
条形图:catplot(kind=“bar”)
在seaborn中,barplot()函数在整个数据集上运行,并且应用一个函数来获得那些统计量(默认为均值)。当每个分类中有多个观测值时,它还可以通过自助采样法计算出一个置信区间,并且通过误差棒的方式绘制出来。
titanic = sns.load_dataset("titanic")
print(len(titanic))
titanic.head()
891
survived | pclass | sex | age | sibsp | parch | fare | embarked | class | who | adult_male | deck | embark_town | alive | alone | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 3 | male | 22.0 | 1 | 0 | 7.2500 | S | Third | man | True | NaN | Southampton | no | False |
1 | 1 | 1 | female | 38.0 | 1 | 0 | 71.2833 | C | First | woman | False | C | Cherbourg | yes | False |
2 | 1 | 3 | female | 26.0 | 0 | 0 | 7.9250 | S | Third | woman | False | NaN | Southampton | yes | True |
3 | 1 | 1 | female | 35.0 | 1 | 0 | 53.1000 | S | First | woman | False | C | Southampton | yes | False |
4 | 0 | 3 | male | 35.0 | 0 | 0 | 8.0500 | S | Third | man | True | NaN | Southampton | no | True |
sns.catplot(kind="bar", x="sex", y="survived", hue="class", data=titanic)
<seaborn.axisgrid.FacetGrid at 0x7fd84c4d7d30>
可以清晰明了地看出来: 女性幸存者高于男性; 舱级高的幸存者高于舱级低的。
catplot(kind=“count”):展示每个分类下观测值的数量
“属于分类变量而非连续变量的直方图”
想要展示每个分类下观测值(样本)的数量而非统计量。这就像是“属于分类变量而非连续变量的直方图”。
仅给一个轴(要水平方向画就x:你的分类变量;垂直方向就y:你的分类变量),另一个轴默认为count了:
如,展示买各个class票的人数:
sns.catplot(kind="count", x="class",data=titanic)
<seaborn.axisgrid.FacetGrid at 0x7fd84cbf1cc0>
sns.catplot(kind="count", x="class", hue="alive",data=titanic)
<seaborn.axisgrid.FacetGrid at 0x7fd847eb19e8>
#也可以将连续型变量当成分类型变量
sns.catplot(kind="count", y="size",data=tips,color='c')
<seaborn.axisgrid.FacetGrid at 0x7fd8474472b0>
catplot(kind=“point”):
sns.catplot(kind="point", x="sex", y ="fare", data=titanic)
<seaborn.axisgrid.FacetGrid at 0x7fd84c6a5470>