天天看点

python数据分析与可视化——利用Seaborn进行绘图

利用Seaborn进行绘图

下面例子中所用数据下载地址——>iris.csv

Matplotlib绘图基本模仿MATLAB绘图库,其绘图风格和MATLAB类似。由于MATLAB绘图风格偏古典,因此,Python开源社区开发了Seaborn绘图模块,对Matplotlib进行封装,绘图效果更符合现代人的审美。

Seaborn属于Matplotlib的一个高级接口,使得作图更加容易。在多数情况下使用Seaborn能做出很具吸引力的图,而使用Matplotlib可以制作具有更多特色的图。应该把Seaborn视为iris.csvMatplotlib的补充,而不是替代物。

使用Seaborn时,使用的导入惯例为:

import seaborn as sns

风格设置用以设置绘图的背景色、风格、字型、字体等。

Seaborn通过set函数实现风格设置。

seaborn.set(context=‘notebook’, style=‘darkgrid’, palette=‘deep’, font=‘sans-serif’, font_scale=1, color_codes=True, rc=None)

利用seaborn.set进行风格设置

import seaborn as sns
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def sinplot(flip=2):
    x = np.linspace(0,20, 50)
    for i in range(1,5):
        plt.plot(x, np.cos(x + i * 0.8) * (9 - 2*i) * flip)
sinplot()

           
python数据分析与可视化——利用Seaborn进行绘图
sns.set(style='darkgrid',font_scale=1.5)
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图

如果需要转换为seaborn默认的绘图设置,只需调用sns.set( )方法即可。

sns.set()
sinplot()
           

设置主题

利用set_style( )是用来设置主题的。

Seaborn有五个预设好的主题: darkgrid, whitegrid,dark,white,和 ticks,默认为darkgrid。

sns.set_style("whitegrid")  
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图

Seaborn将matplotlib的参数划分为两个独立的组合。第一组是设置绘图的外观风格的,第二组主要将绘图的各种元素按比例缩放的,以至可以嵌入到不同的背景环境中。控制这些参数的接口主要有两对方法:

控制风格:axes_style(), set_style()

缩放绘图:plotting_context(), set_context()

每对方法中的第一个方法(axes_style(), plotting_context())会返回一组字典参数,而第二个方法(set_style(), set_context())会设置matplotlib的默认参数。

利用set_style( )是用来设置主题的。Seaborn有五个预设的主题: darkgrid, whitegrid,dark,white,和 ticks,默认为darkgrid。

sns.set_style("whitegrid")  
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图

在seaborn中,可以利用despine()方法移除绘图中顶部和右侧的轴线。

sinplot()
sns.despine()
           
python数据分析与可视化——利用Seaborn进行绘图

despine()方法中可以利用offset参数讲轴线进行偏置,另外,当刻度没有完全覆盖整个坐标轴的的范围时,利用trim参数限制已有坐标轴的范围。

sinplot()
sns.despine(offset=20, trim=True)
           
python数据分析与可视化——利用Seaborn进行绘图

也可以通过despine()控制哪个脊柱将被移除。

sinplot()
sns.despine(left=True)
           
python数据分析与可视化——利用Seaborn进行绘图

也可以通过despine()控制哪个脊柱将被移除。

sinplot()
sns.set(style='whitegrid',palette='muted',color_codes=True)
sns.despine(left=True,bottom=True)
           
python数据分析与可视化——利用Seaborn进行绘图

除了选用预设的风格外,可以利用with 语句使用axes_style()方法设置临时绘图参数。

with sns.axes_style("darkgrid"):
    plt.subplot(2,1,1)
    sinplot( )
plt.subplot(2,1, 2)
sinplot(-1)
           
python数据分析与可视化——利用Seaborn进行绘图

seaborn中通过set_context()设置缩放参数,预设的参数有paper, notebook, talk, poster。默认为notebook。

sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图
sns.set_context("paper")
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图
sns.set_context("notebook", font_scale=1.8, rc={"lines.linewidth": 1.5})
sinplot()
           
python数据分析与可视化——利用Seaborn进行绘图

常用的绘图

直方图和密度曲线图

Seaborn中利用distplot( )和 kdeplot( )绘制直方图和密度曲线图,distplot( )为hist加强版,默认情况下绘制一个直方图,并嵌套一个对应的密度图。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set(palette="muted",color_codes=True)
rs=np.random.RandomState(10)
d=rs.normal(size=100)
f,axes=plt.subplots(2, 2, figsize=(7, 7), sharex=True)
sns.distplot(d, kde=False, color="b", ax=axes[0,0])
sns.distplot(d, hist=False, rug=True, color="r", ax=axes[0,1])
sns.distplot(d, hist=False,color="g", kde_kws={"shade":True}, ax=axes[1,0])
sns.distplot(d, color="m", ax=axes[1,1])
plt.show()

           
python数据分析与可视化——利用Seaborn进行绘图

散点图

在Seaborn中,利用stripplot绘制各变量在每个类别的值。

例:在iris数据集中,显示Petal.Width在Species上值的分布

sns.set(style='white',color_codes=True) #设置样式 
sns.stripplot(x=df_iris['Species'],y= df_iris['Petal.Width'],data=df_iris)
sns.despine()   #去坐标轴
           
python数据分析与可视化——利用Seaborn进行绘图

如果需要看清每个数据点,可以使用swarmplot函数

sns.swarmplot(x=df_iris['Species'],y= df_iris['Petal.Width'],data=df_iris)
sns.despine()   #去坐标轴
           
python数据分析与可视化——利用Seaborn进行绘图

箱型图

有时候,散点图表达的值的分布信息有限,因此需要一些其它的绘图。箱线图可以观察四分位数、中位数和极值。Seaborn中利用boxplot( )绘制箱线图。

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.boxplot(x=df_iris['Species'],y = df_iris['Petal.Width'])  
plt.show()
           
python数据分析与可视化——利用Seaborn进行绘图
df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.set(style="ticks")  
sns.boxplot(x=df_iris['Species'],y = df_iris['Petal.Width'])  
plt.show()
           
python数据分析与可视化——利用Seaborn进行绘图

pairplot

在seaborn中利用 pairplot()实现数据特征的两两对比。默认是所有特征,可以通过vars参数指定部分特征。

pairplot主要展现的是变量两两之间的关系(线性或非线性,有无较为明显的相关关系)

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.set(style="ticks")  
g = sns.pairplot(df_iris,vars=['Sepal.Length', 'Petal.Length'])
           
python数据分析与可视化——利用Seaborn进行绘图

小提琴图

小提琴图其实是箱线图与核密度图的结合,箱线图展示了分位数的位置,小提琴图则展示了任意位置的密度,通过小提琴图可以知道哪些位置的密度较高。在图中,白点是中位数,黑色盒型的范围是下四分位点到上四分位点,细黑线表示须。外部形状即为核密度估计(在概率论中用来估计未知的密度函数,属于非参数检验方法之一)。

sns.set_style("whitegrid")
df_iris=pd.read_csv('D:\dataset\iris.csv')
ax = sns.violinplot(x=df_iris['Petal.Length'])
           
python数据分析与可视化——利用Seaborn进行绘图

柱状图

在Seaborn中使用barplot函数绘制柱状图,默认情况下,绘制的y轴是平均值。

df_iris=pd.read_csv('D:\dataset\iris.csv')
sns.barplot(x=df_iris['Species'],y=df_iris['Petal.Length'],data=df_iris)

           
python数据分析与可视化——利用Seaborn进行绘图

在柱状图中,经常会绘制类别的计数柱状图,在matplotlib中需要对DataFrame进行计算,而在Seaborn中则使用countplot函数即可。

python数据分析与可视化——利用Seaborn进行绘图

多变量图

在matplotlib中,为了绘制两个变量的分布关系,常使用散点图的方法。在Seaborn中,使用jointplot函数绘制一个多面板图,不仅可以显示两个变量的关系,还可以显示每个单变量的分布情况。

python数据分析与可视化——利用Seaborn进行绘图

在jointplot函数中,改变kind参数为kde,但变量的分布就用密度图来代替,而散点图则会被等高线图代替。

python数据分析与可视化——利用Seaborn进行绘图

回归图

绘制回归图可以揭示两个变量间的线性关系。Seaborn中,使用regplot函数绘制回归图。

python数据分析与可视化——利用Seaborn进行绘图