0%

Matplotlib的Seaborn风格可视化

Seaborn风格可视化

什么是seaborn

​ Seaborn是基于matplotlib的图形可视化python包。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。Seaborn是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn能做出很具有吸引力的图,而使用matplotlib就能制作具有更多特色的图。应该把Seaborn视为matplotlib的补充,而不是替代物。同时它能高度兼容numpy与pandas数据结构以及scipy与statsmodels等统计模式。

seaborn API

Seaborn 要求原始数据的输入类型为 pandas 的 Dataframe 或 Numpy 数组,画图函数有以下几种形式:

  • sns.图名(x=’X轴 列名’, y=’Y轴 列名’, data=原始数据df对象)
  • sns.图名(x=’X轴 列名’, y=’Y轴 列名’, hue=’分组绘图参数’, data=原始数据df对象)
  • sns.图名(x=np.array, y=np.array[, …])
1
2
3
4
5
6
import numpy as np
import pandas as pd
import scipy as stats
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

基本绘图设置

1
2
3
4
5
6
7
# 创建正弦函数
def sinplot(flip=1):
x = np.linspace(0, 14, 100)
for i in range(1,7):
plt.plot(x, np.sin(x+i*.5)*(7-i)*flip)

sinplot()

简单切换成Seaborn风格

1
2
3
4
# 切换Seaborn风格
sns.set()
fig = plt.figure(figsize=(8,6))
sinplot()

png

1
2
3
4
5
6
7
8
9
10
11
# 切换seaborn图标风格
fig = plt.figure(figsize=(10,6), facecolor='white')
ax1 = fig.add_subplot(211)
sns.set_style('whitegrid')
data = np.random.normal(size=(20,6))+np.arange(6)/2
sns.boxplot(data=data)
plt.title('style-whitegrid')

ax2 = fig.add_subplot(212)
sns.set_style('dark')
sinplot()

png

设置图标坐标轴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#despine()
# seaborn.despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False)

# 设置风格
sns.set_style("ticks")

# 创建图表
fig = plt.figure(figsize=(6,9))
plt.subplots_adjust(hspace=0.3)

ax1 = fig.add_subplot(3,1,1)
sinplot()
# 删除了上、右坐标轴
sns.despine()

ax2 = fig.add_subplot(3,1,2)
sns.violinplot(data=data)
# offset:与坐标轴之间的偏移
# trim:为True时,将坐标轴限制在数据最大最小值
#sns.despine(offset=10, trim=True)


ax3 = fig.add_subplot(3,1,3)
# top, right, left, bottom:布尔型,为True时不显示
#sns.despine(left=True, right = False)
sns.boxplot(data=data, palette="deep")
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b20e4f7a58>

png

设置局部图标风格

1
2
3
4
5
6
7
8
9
with sns.axes_style("darkgrid"):
plt.subplot(211)
sinplot()
# 设置局部图表风格,用with做代码块区分

sns.set_style("whitegrid")
plt.subplot(212)
sinplot()
# 外部表格风格

png

设置显示比例

1
2
3
4
5
6
7
8
9
#set_context()
# 选择包括:'paper', 'notebook', 'talk', 'poster'

## 与上面的cell比较你就会发现不同

sns.set_style("whitegrid")
sns.set_context("poster")
plt.subplot(212)
sinplot()

png

调色板

1
2
3
4
5
6
7
8
9
# color_palette()
# 默认6种颜色:deep, muted, pastel, bright, dark, colorblind
# seaborn.color_palette(palette=None, n_colors=None, desat=None)
current_palette = sns.color_palette()
print(type(current_palette))


# sns.palplot(current_palette[2:4])
sns.palplot(current_palette)
1
<class 'seaborn.palettes._ColorPalette'>

png

颜色风格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 颜色风格内容:Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, 
# BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r, GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r,
# Paired, Paired_r, Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r, Purples,
# Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1, Set1_r, Set2, Set2_r, Set3,
# Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr, YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r,
# autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix,
# cubehelix_r, flag, flag_r, gist_earth, gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow,
# gist_rainbow_r, gist_stern, gist_stern_r, gist_yarg, gist_yarg_r, gnuplot, gnuplot2, gnuplot2_r, gnuplot_r, gray, gray_r, hot, hot_r, hsv,
# hsv_r, icefire, icefire_r, inferno, inferno_r, jet, jet_r, magma, magma_r, mako, mako_r, nipy_spectral, nipy_spectral_r, ocean, ocean_r,
# pink, pink_r, plasma, plasma_r, prism, prism_r, rainbow, rainbow_r, rocket, rocket_r, seismic, seismic_r, spectral, spectral_r, spring,
# spring_r, summer, summer_r, terrain, terrain_r, viridis, viridis_r, vlag, vlag_r, winter, winter_r

sns.palplot(sns.color_palette('Accent',12))
sns.palplot(sns.color_palette('Accent_r',8))

png

png

设置饱和度和亮度

1
2
3
4
sns.palplot(sns.hls_palette(4,l=.3,s=.8))

# l->亮度
# s->饱和度

png

设置颜色线性变化

1
2
3
4
5
6
7
8
9
10
11
#设置颜色线性变化
sns.palplot(sns.cubehelix_palette(16, gamma=2))
sns.palplot(sns.cubehelix_palette(16, start=.5, rot=.75))
sns.palplot(sns.cubehelix_palette(16,start=0.5, rot=0, dark=0.95, reverse=True))

# n_colors → 颜色个数
# start → 值区间在0-3,开始颜色
# rot → 颜色旋转角度
# gamma → 颜色伽马值,越大颜色越暗
# dark,light → 值区间0-1,颜色深浅
# reverse → 布尔值,默认为False,由浅到深

png

png

png

创建分散颜色

1
2
3
4
5
6
plt.figure(figsize = (8,6))
x = np.arange(25).reshape(5, 5)
# 创建分散颜色
cmap = sns.diverging_palette(200, 20, sep=20, as_cmap=True)

sns.heatmap(x, cmap=cmap)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21a370cf8>

png

1
2
3
4
5
6
7
8
9
sns.set_style('whitegrid')
fig=plt.figure(figsize=(12,8))
with sns.color_palette('PuBuGn_d'):
plt.subplot(211)
sinplot()

sns.set_palette('husl')
plt.subplot(212)
sinplot()

png

1
2
3
4
5
6
sns.set_style('darkgrid')
sns.set_context('paper')

import warnings
warnings.filterwarnings('ignore')
#不再发出警告

分布数据可视化

直方图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#直方图
#设计随即种子
rs = np.random.RandomState(10)
s = pd.Series(rs.randn(100)*100)
sns.distplot(s, bins=10, hist=True, kde=False, norm_hist=False,
rug=True,vertical=False,color='y', label='distplot', axlabel='x')

plt.legend()
# bins → 箱数
# hist、ked → 是否显示箱/密度曲线
# norm_hist → 直方图是否按照密度来显示
# rug → 是否显示数据分布情况
# vertical → 是否水平显示
# color → 设置颜色
# label → 图例
# axlabel → x轴标注
1
<matplotlib.legend.Legend at 0x1b20e65e4e0>

png

1
2
3
4
5
6
sns.distplot(s, rug=True, rug_kws={'color':'g'},
kde_kws={"color": "k", "lw": 1, "label": "KDE",'linestyle':'--'},
# 设置密度曲线颜色,线宽,标注、线形
hist_kws={"histtype": "step", "linewidth": 1,"alpha": 1, "color": "g"})
# 设置箱子的风格、线宽、透明度、颜色
# 风格包括:'bar', 'barstacked', 'step', 'stepfilled'
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21bc8e828>

png

密度图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 密度图 - kdeplot()
# 单个样本数据密度分布图

sns.kdeplot(s,
shade = False, # 是否填充
color = 'b', # 设置颜色
vertical = False # 设置是否水平
)

sns.kdeplot(s,bw=5, label="bw: 0.2",
linestyle = '-',linewidth = 1.2,alpha = 0.5)

sns.kdeplot(s,bw=20, label="bw: 2",
linestyle = '-',linewidth = 1.2,alpha = 0.5)
# bw → 控制拟合的程度,类似直方图的箱数

sns.rugplot(s,height = 0.1,color = 'k',alpha = 0.5)
# 数据频率分布图
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21babf470>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 密度图 - kdeplot()
# 两个样本数据密度分布图

rs = np.random.RandomState(2) # 设定随机数种子
df = pd.DataFrame(rs.randn(100,2),
columns = ['A','B'])
sns.kdeplot(df['A'],df['B'],
cbar = True, # 是否显示颜色图例
shade = True, # 是否填充
cmap = 'Reds', # 设置调色盘
shade_lowest=False, # 最外围颜色是否显示
n_levels = 10 # 曲线个数(如果非常多,则会越平滑)
)
# 两个维度数据生成曲线密度图,以颜色作为密度衰减显示

sns.rugplot(df['A'], color="g", axis='x',alpha = 0.5)
sns.rugplot(df['B'], color="r", axis='y',alpha = 0.5)
# 注意设置x,y轴
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21bb63470>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 密度图 - kdeplot()
# 两个样本数据密度分布图
# 多个密度图

rs1 = np.random.RandomState(2)
rs2 = np.random.RandomState(5)
df1 = pd.DataFrame(rs1.randn(100,2)+2,columns = ['A','B'])
df2 = pd.DataFrame(rs2.randn(100,2)-2,columns = ['A','B'])
# 创建数据

sns.kdeplot(df1['A'],df1['B'],cmap = 'Greens',
shade = True,shade_lowest=False)
sns.kdeplot(df2['A'],df2['B'],cmap = 'Blues',
shade = True,shade_lowest=False)
# 创建图表
#sns.rugplot(df2['A']+df1['A'], color="g", axis='x',alpha = 0.5)
#sns.rugplot(df2['B']+df1['B'], color="r", axis='y',alpha = 0.5)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21be56278>

png

综合散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 综合散点图 - jointplot()
# 散点图 + 分布图

rs = np.random.RandomState(2)
df = pd.DataFrame(rs.randn(200,2),columns = ['A','B'])


sns.jointplot(x=df['A'], y=df['B'], # 设置xy轴,显示columns名称
data=df, # 设置数据
color = 'k', # 设置颜色
s = 50, edgecolor="w",linewidth=1, # 设置散点大小、边缘线颜色及宽度(只针对scatter)
kind = 'scatter', # 设置类型:“scatter”、“reg”、“resid”、“kde”、“hex”
space = 0.2, # 设置散点图和布局图的间距
size = 8, # 图表大小(自动调整为正方形)
ratio = 5, # 散点图与布局图高度比,整型
marginal_kws=dict(bins=15, rug=True) # 设置柱状图箱数,是否设置rug
)
1
<seaborn.axisgrid.JointGrid at 0x1b21bee2be0>

png

1
2
3
4
5
6
7
8
9
10
# 综合散点图 - jointplot()
# 散点图 + 分布图
# 六边形图

df = pd.DataFrame(rs.randn(500,2),columns = ['A','B'])


with sns.axes_style("white"):
sns.jointplot(x=df['A'], y=df['B'],data = df, kind="hex", color="g",
marginal_kws=dict(bins=20))

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 综合散点图 - jointplot()
# 散点图 + 分布图
# 密度图

rs = np.random.RandomState(15)
df = pd.DataFrame(rs.randn(300,2),columns = ['A','B'])
# 创建数据

g = sns.jointplot(x=df['A'], y=df['B'],data = df,
kind="kde", color="k",
shade_lowest=False)
# 创建密度图

g.plot_joint(plt.scatter,c="w", s=30, linewidth=1, marker="*")
# 添加散点图
1
<seaborn.axisgrid.JointGrid at 0x1b21c4325f8>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 综合散点图 - JointGrid()
# 可拆分绘制的散点图
# plot_joint() + ax_marg_x.hist() + ax_marg_y.hist()

sns.set_style("white")
# 设置风格

tips = sns.load_dataset("tips")
print(tips.head())
# 导入数据

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 创建一个绘图表格区域,设置好x、y对应数据

g.plot_joint(plt.scatter, color ='m', edgecolor = 'white') # 设置框内图表,scatter
g.ax_marg_x.hist(tips["total_bill"], color="b", alpha=.6,
bins=np.arange(0, 60, 3)) # 设置x轴直方图,注意bins是数组
g.ax_marg_y.hist(tips["tip"], color="r", alpha=.6,
orientation="horizontal",
bins=np.arange(0, 12, 1)) # 设置x轴直方图,注意需要orientation参数

from scipy import stats
g.annotate(stats.pearsonr)
# 设置标注,可以为pearsonr,spearmanr

plt.grid(linestyle = '--')
1
2
3
4
5
6
   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

png

1
2
3
4
5
6
7
8
9
10
11
# 综合散点图 - JointGrid()
# 可拆分绘制的散点图
# plot_joint() + plot_marginals()

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 创建一个绘图表格区域,设置好x、y对应数据

g = g.plot_joint(plt.scatter,color="g", s=40, edgecolor="white") # 绘制散点图
plt.grid(linestyle = '--')

g.plot_marginals(sns.distplot, kde=True, color="g") # 绘制x,y轴直方图
1
<seaborn.axisgrid.JointGrid at 0x1b21c630da0>

png

1
2
3
4
5
6
7
8
9
10
11
12
# 综合散点图 - JointGrid()
# 可拆分绘制的散点图
# plot_joint() + plot_marginals()
# kde - 密度图

g = sns.JointGrid(x="total_bill", y="tip", data=tips)
# 创建一个绘图表格区域,设置好x、y对应数据

g = g.plot_joint(sns.kdeplot,cmap = 'Reds_r') # 绘制密度图
plt.grid(linestyle = '--')

g.plot_marginals(sns.kdeplot, shade = True, color="r") # 绘制x,y轴密度图
1
<seaborn.axisgrid.JointGrid at 0x1b21d7aef60>

png

矩阵散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 矩阵散点图 - pairplot()

sns.set_style("white")
# 设置风格

iris = sns.load_dataset("iris")
print(iris.head())
# 读取数据

sns.pairplot(iris,
kind = 'scatter', # 散点图/回归分布图 {‘scatter’, ‘reg’}
diag_kind="hist", # 直方图/密度图 {‘hist’, ‘kde’}
hue="species", # 按照某一字段进行分类
palette="husl", # 设置调色板
markers=["o", "s", "D"], # 设置不同系列的点样式(这里根据参考分类个数)
size = 2, # 图表大小
)
1
2
3
4
5
6
   sepal_length  sepal_width  petal_length  petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
1
<seaborn.axisgrid.PairGrid at 0x1b21d8a44e0>

png

1
2
3
4
5
6
# 矩阵散点图 - pairplot()
# 只提取局部变量进行对比

sns.pairplot(iris,vars=["sepal_width", "sepal_length"],
kind = 'reg', diag_kind="kde",
hue="species", palette="husl")
1
<seaborn.axisgrid.PairGrid at 0x1b21e003c18>

png

1
2
3
4
5
6
7
8
9
# 矩阵散点图 - pairplot()
# 其他参数设置

sns.pairplot(iris, diag_kind="kde", markers="+",
plot_kws=dict(s=50, edgecolor="b", linewidth=1),
# 设置点样式
diag_kws=dict(shade=True)
# 设置密度图样式
)
1
<seaborn.axisgrid.PairGrid at 0x1b21c37be48>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#  矩阵散点图 - PairGrid()
# 可拆分绘制的散点图
# map_diag() + map_offdiag()

g = sns.PairGrid(iris,hue="species",palette = 'hls',
vars = ['sepal_length','sepal_width','petal_length','petal_width'], # 可筛选
)
# 创建一个绘图表格区域,设置好x、y对应数据,按照species分类

g.map_diag(plt.hist,
histtype = 'barstacked', # 可选:'bar', 'barstacked', 'step', 'stepfilled'
linewidth = 1, edgecolor = 'w')
# 对角线图表,plt.hist/sns.kdeplot

g.map_offdiag(plt.scatter,
edgecolor="w", s=40,linewidth = 1, # 设置点颜色、大小、描边宽度
)
# 其他图表,plt.scatter/plt.bar...

g.add_legend()
# 添加图例
1
<seaborn.axisgrid.PairGrid at 0x1b218fe3f98>

png

1
2
3
4
5
6
7
8
# 矩阵散点图 - PairGrid()
# 可拆分绘制的散点图
# map_diag() + map_lower() + map_upper()

g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot, lw=3) # 设置对角线图表
g.map_upper(plt.scatter, color = 'r') # 设置对角线上端图表
g.map_lower(sns.kdeplot, cmap="Blues_d") # 设置对角线下端图表
1
<seaborn.axisgrid.PairGrid at 0x1b21ee966a0>

png

分类数据可视化

分类散点图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# stripplot()
# 按照不同类别对样本数据进行分布散点图绘制

tips = sns.load_dataset("tips")
print(tips.head())


sns.stripplot(x="day", # x → 设置分组统计字段
y="total_bill", # y → 数据分布统计字段
# 这里xy数据对调,将会使得散点图横向分布
data=tips, # data → 对应数据
jitter = True, # jitter → 当点数据重合较多时,用该参数做一些调整,也可以设置间距如:jitter = 0.1
size = 5, edgecolor = 'w',linewidth=1,marker = 'o' # 设置点的大小、描边颜色或宽度、点样式
)
1
2
3
4
5
6
   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
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21f971320>

png

1
2
3
4
5
# stripplot()
# 通过hue参数再分类

sns.stripplot(x="sex", y="total_bill", hue="day",
data=tips, jitter=True)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21f9b2b00>

png

1
2
3
4
5
6
7
8
# stripplot()
# 设置调色盘

sns.stripplot(x="sex", y="total_bill", hue="day",
data=tips, jitter=True,
palette="Set2", # 设置调色盘
dodge=True, # 是否拆分
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fc11198>

png

1
2
3
4
5
6
7
8
9
# stripplot()
# 筛选分类类别

print(tips['day'].value_counts())
# 查看day字段的唯一值

sns.stripplot(x="day", y="total_bill", data=tips,jitter = True,
order = ['Sat','Sun'])
# order → 筛选类别
1
2
3
4
5
Sat     87
Sun 76
Thur 62
Fri 19
Name: day, dtype: int64
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fc8c748>

png

分簇散点图

1
2
3
4
5
6
7
# swarmplot()
# 分簇散点图

sns.swarmplot(x="total_bill", y="day", data=tips,
size = 5, edgecolor = 'w',linewidth=1,marker = 'o',
palette = 'Reds')
# 用法和stripplot类似
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fcdef28>

png

箱型图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# boxplot()

sns.boxplot(x="day", y="total_bill", data=tips,
linewidth = 2, # 线宽
width = 0.8, # 箱之间的间隔比例
fliersize = 3, # 异常点大小
palette = 'hls', # 设置调色板
whis = 1.5, # 设置IQR
notch = True, # 设置是否以中值做凹槽
order = ['Thur','Fri','Sat','Sun'], # 筛选类别
)
# 绘制箱型图

#sns.swarmplot(x="day", y="total_bill", data=tips,color ='k',size = 3,alpha = 0.8)
# 可以添加散点图
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fd32710>

png

1
2
3
# 通过hue参数再分类
sns.boxplot(x="day", y="total_bill", data=tips,
hue = 'smoker', palette = 'Reds')
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fdce5c0>

png

小提琴图

1
2
3
4
5
6
7
8
9
10
11
12
13
# violinplot()


sns.violinplot(x="day", y="total_bill", data=tips,
linewidth = 2, # 线宽
width = 0.8, # 箱之间的间隔比例
palette = 'hls', # 设置调色板
order = ['Thur','Fri','Sat','Sun'], # 筛选类别
scale = 'area', # 测度小提琴图的宽度:area-面积相同,count-按照样本数量决定宽度,width-宽度一样
gridsize = 50, # 设置小提琴图边线的平滑度,越高越平滑
inner = 'box', # 设置内部显示类型 → “box”, “quartile”, “point”, “stick”, None
#bw = 0.8 # 控制拟合程度,一般可以不设置
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21feb0d68>

png

1
2
3
4
5
6
# 通过hue参数再分类

sns.violinplot(x="day", y="total_bill", data=tips,
hue = 'smoker', palette="muted",
split=True, # 设置是否拆分小提琴图
inner="quartile")
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21ff37940>

png

1
2
3
4
5
# 结合散点图

sns.violinplot(x="day", y="total_bill", data=tips, palette = 'hls', inner = None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5)
# 插入散点图
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21fff0e80>

png

LV图

1
2
3
4
5
6
7
8
9
10
11
12
#  lvplot()
sns.lvplot(x="day", y="total_bill", data=tips, palette="mako",
#hue = 'smoker',
width = 0.8, # 箱之间间隔比例
linewidth = 12,
scale = 'area', # 设置框的大小 → “linear”、“exonential”、“area”
k_depth = 'proportion', # 设置框的数量 → “proportion”、“tukey”、“trustworthy”
)
# 绘制LV图

sns.swarmplot(x="day", y="total_bill", data=tips,color ='k',size = 3,alpha = 0.8)
# 可以添加散点图
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b22101c400>

png

分类统计图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# barplot()
# 柱状图 - 置信区间估计
# 置信区间:样本均值 + 抽样误差

titanic = sns.load_dataset("titanic")
#print(titanic.head())
#print('-----')
# 加载数据

sns.barplot(x="sex", y="survived", hue="class", data=titanic,
palette = 'hls',
order = ['male','female'], # 筛选类别
capsize = 0.05, # 误差线横向延伸宽度
saturation=.8, # 颜色饱和度
errcolor = 'gray',errwidth = 2, # 误差线颜色,宽度
ci = 'sd' # 置信区间误差 → 0-100内值、'sd'、None
)
#print(titanic.groupby(['sex','class']).mean()['survived'])
#print(titanic.groupby(['sex','class']).std()['survived'])
# 计算数据
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b2210a1048>

png

1
2
3
4
5
6
7
# barplot()
# 柱状图 - 置信区间估计

sns.barplot(x="day", y="total_bill", hue="sex", data=tips,
palette = 'Blues',edgecolor = 'w')
tips.groupby(['day','sex']).mean()
# 计算数据
total_bill tip size
day sex
Thur Male 18.714667 2.980333 2.433333
Female 16.715312 2.575625 2.468750
Fri Male 19.857000 2.693000 2.100000
Female 14.145556 2.781111 2.111111
Sat Male 20.802542 3.083898 2.644068
Female 19.680357 2.801786 2.250000
Sun Male 21.887241 3.220345 2.810345
Female 19.872222 3.367222 2.944444

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 1、barplot()
# 柱状图 - 置信区间估计

crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False)
print(crashes.head())
# 加载数据

f, ax = plt.subplots(figsize=(6, 15))
# 创建图表

sns.set_color_codes("pastel")
sns.barplot(x="total", y="abbrev", data=crashes,
label="Total", color="b",edgecolor = 'w')
# 设置第一个柱状图

sns.set_color_codes("muted")
sns.barplot(x="alcohol", y="abbrev", data=crashes,
label="Alcohol-involved", color="b",edgecolor = 'w')
# 设置第二个柱状图

ax.legend(ncol=2, loc="lower right")
sns.despine(left=True, bottom=True)
1
2
3
4
5
6
7
8
9
10
11
12
13
    total  speeding  alcohol  not_distracted  no_previous  ins_premium  \
40 23.9 9.082 9.799 22.944 19.359 858.97
34 23.9 5.497 10.038 23.661 20.554 688.75
48 23.8 8.092 6.664 23.086 20.706 992.61
3 22.4 4.032 5.824 21.056 21.280 827.34
17 21.4 4.066 4.922 16.692 16.264 872.51

ins_losses abbrev
40 116.29 SC
34 109.72 ND
48 152.56 WV
3 142.39 AR
17 137.13 KY

png

1
2
3
4
5
6
7
#  countplot()
# 计数柱状图

sns.countplot(x="class", hue="who", data=titanic,palette = 'magma')
#sns.countplot(y="class", hue="who", data=titanic,palette = 'magma')
# x/y → 以x或者y轴绘图(横向,竖向)
# 用法和barplot相似
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b22117aac8>

png

1
2
3
4
5
6
7
8
9
10
11
12
# pointplot()
# 折线图 - 置信区间估计

sns.pointplot(x="time", y="total_bill", hue = 'smoker',data=tips,
palette = 'hls',
dodge = True, # 设置点是否分开
join = True, # 是否连线
markers=["o", "x"], linestyles=["-", "--"], # 设置点样式、线型
)
tips.groupby(['time','smoker']).mean()['total_bill']
# 计算数据
# # 用法和barplot相似
1
2
3
4
5
6
time    smoker
Lunch Yes 17.399130
No 17.050889
Dinner Yes 21.859429
No 20.095660
Name: total_bill, dtype: float64

png

线性数据可视化

基本使用

1
2
3
4
5
6
7
8
9
10
11
# 基本用法

tips = sns.load_dataset("tips")
print(tips.head())
# 加载数据

sns.lmplot(x="total_bill", y="tip", hue = 'smoker',data=tips,palette="Set1",
ci = 70, # 误差值
size = 5, # 图表大小
markers = ['+','o'], # 点样式
)
1
2
3
4
5
6
   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
1
<seaborn.axisgrid.FacetGrid at 0x1b21c57d7b8>

png

多表格

1
sns.lmplot(x="total_bill", y="tip", col="smoker", data=tips)
1
<seaborn.axisgrid.FacetGrid at 0x1b2215774e0>

png

1
2
3
4
5
6
7
# 多图表1

sns.lmplot(x="size", y="total_bill", hue="day", col="day",data=tips,
aspect=0.6, # 长宽比
x_jitter=.30, # 给x或者y轴随机增加噪音点
col_wrap=4, # 每行的列数
)
1
<seaborn.axisgrid.FacetGrid at 0x1b2216276a0>

png

1
2
3
4
5
# 多图表2

sns.lmplot(x="total_bill", y="tip", row="sex", col="time",data=tips, size=4)
# 行为sex字段,列为time字段
# x轴total_bill, y轴tip
1
<seaborn.axisgrid.FacetGrid at 0x1b22160a400>

png

非线性回归

1
2
3
4
# 非线性回归

sns.lmplot(x="total_bill", y="tip",data=tips,
order = 2)
1
<seaborn.axisgrid.FacetGrid at 0x1b2214d7b00>

png

其他图表可视化

时间线图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#  tsplot()


x = np.linspace(0, 15, 31)
data = np.sin(x) + np.random.rand(10, 31) + np.random.randn(10, 1)
#print(data.shape)
#print(pd.DataFrame(data).head())
# 创建数据

sns.tsplot(data=data,
err_style="ci_band", # 误差数据风格,可选:ci_band, ci_bars, boot_traces, boot_kde, unit_traces, unit_points
interpolate=True, # 是否连线
ci = [40,70,90], # 设置误差区间
color = 'r' # 设置颜色
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b21668c860>

png

1
2
3
sns.tsplot(data=data, err_style="boot_traces", 
n_boot=300 # 迭代次数
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b216533048>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
gammas = sns.load_dataset("gammas")
print(gammas.head())
print('数据量为:%i条' % len(gammas))
print('timepoint为0.0时的数据量为:%i条' % len(gammas[gammas['timepoint'] == 0]))
print('timepoint共有%i个唯一值' % len(gammas['timepoint'].value_counts()))
#print(gammas['timepoint'].value_counts()) # 查看唯一值具体信息
# 导入数据

sns.tsplot(time="timepoint", # 时间数据,x轴
value="BOLD signal", # y轴value
unit="subject", #
condition="ROI", # 分类
data=gammas)
1
2
3
4
5
6
7
8
9
   timepoint  ROI  subject  BOLD signal
0 0.0 IPS 0 0.513433
1 0.0 IPS 1 -0.414368
2 0.0 IPS 2 0.214695
3 0.0 IPS 3 0.814809
4 0.0 IPS 4 -0.894992
数据量为:6000条
timepoint为0.0时的数据量为:60条
timepoint共有100个唯一值
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b221f95a58>

png

热图

1
2
3
4
5
6
7
8
9
# 热图 - heatmap()
# 简单示例

df = pd.DataFrame(np.random.rand(10,15))
# 创建数据 - 10*12图表

sns.heatmap(df, # 加载数据
vmin=0, vmax=1 # 设置图例最大最小值
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b221faac88>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# heatmap()
# 参数设置

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")
#print(flights.head())
# 加载数据

sns.heatmap(flights,
annot = True, # 是否显示数值
fmt = 'd', # 格式化字符串
linewidths = 0.2, # 格子边线宽度
#center = 100, # 调色盘的色彩中心值,若没有指定,则以cmap为主
#cmap = 'Reds', # 设置调色盘
cbar = True, # 是否显示图例色带
#cbar_kws={"orientation": "horizontal"}, # 是否横向显示图例色带
#square = True, # 是否正方形显示图表
)
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b223040588>

png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#  heatmap()
# 绘制半边热图

sns.set(style="white")
# 设置风格

rs = np.random.RandomState(33)
d = pd.DataFrame(rs.normal(size=(100, 26)))
corr = d.corr() # 求解相关性矩阵表格
# 创建数据

mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# 设置一个“上三角形”蒙版

cmap = sns.diverging_palette(220, 10, as_cmap=True)
# 设置调色盘

sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
square=True, linewidths=0.2)
# 生成半边热图
1
<matplotlib.axes._subplots.AxesSubplot at 0x1b2231f3128>

png

图标矩阵

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
attend = sns.load_dataset("attention")
print(attend.head())
# 加载数据

g = sns.FacetGrid(attend, col="subject", col_wrap=5, # 设置每行的图表数量
size=1.5)
g.map(plt.plot, "solutions", "score",
marker="o",color = 'gray',linewidth = 2)
# 绘制图表矩阵

g.set(xlim = (0,4),
ylim = (0,10),
xticks = [0,1,2,3,4],
yticks = [0,2,4,6,8,10]
)
# 设置x,y轴刻度
1
2
3
4
5
6
   Unnamed: 0  subject attention  solutions  score
0 0 1 divided 1 2.0
1 1 2 divided 1 3.0
2 2 3 divided 1 3.0
3 3 4 divided 1 5.0
4 4 5 divided 1 4.0
1
<seaborn.axisgrid.FacetGrid at 0x1b22328cb00>

png

坚持原创技术分享,您的支持将鼓励我继续创作!