天天看点

Python绘图总结(seaborn篇)之数据分布

学习https://seaborn.pydata.org 记录,描述不一定准确,具体请参考官网

%matplotlib inline
import numpy as np
import pandas as pd
from scipy import stats, integrate
import seaborn as sns
import matplotlib.pyplot as plt
# plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
# plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号

# seaborn中文乱码解决方案
from matplotlib.font_manager import FontProperties
myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=)
sns.set(font=myfont.get_name())
           

1、distplot() 加强直方图

np.random.seed()
x = np.random.normal(size=)

fig, axes = plt.subplots(,,figsize=(, ))  
sns.distplot(x, ax = axes[,])  # 默认
sns.distplot(x, ax = axes[,], kde=False) # 隐藏数据趋势线kde
sns.distplot(x, ax = axes[,], hist=False, rug=True)  # 隐藏直方图hist
sns.distplot(x, ax = axes[,], kde=False, fit=stats.gamma)  # 显示数据紧密度fit

axes[,].set_title('默认')
axes[,].set_title('隐藏趋势线')
axes[,].set_title('隐藏直方图')
axes[,].set_title('显示数据紧密度线')
           
Python绘图总结(seaborn篇)之数据分布

2、kdeplot() 密度曲线图

fig, axes = plt.subplots(,,figsize=(, )) 
sns.kdeplot(x, shade=True, ax = axes[])  # shade=True 阴影
sns.kdeplot(x, bw=, label="bw: 0.2", ax = axes[])
sns.kdeplot(x, bw=, label="bw: 2", ax = axes[])

cmap = sns.cubehelix_palette(as_cmap=True, dark=, light=, reverse=True)
sns.kdeplot(df.x, df.y, cmap=cmap, n_levels=, shade=True, ax = axes[])
           
Python绘图总结(seaborn篇)之数据分布

3、rugplot() 条码/密度

fig, axes = plt.subplots(,,figsize=(, ))  
sns.kdeplot(x, ax = axes[], shade=True, cut=-)  # cut默认为3
sns.rugplot(x, ax = axes[])

sns.kdeplot(df.x, df.y, ax = axes[])            # kdeplot() 线条趋势
sns.rugplot(df.x, color="g", ax = axes[])       # rugplot() X轴条码
sns.rugplot(df.y, vertical=True, ax = axes[])   # rugplot() Y轴条码
           
Python绘图总结(seaborn篇)之数据分布

4、jointplot() 联合分布

mean, cov = [, ], [(, ), (, )]
data = np.random.multivariate_normal(mean, cov, )
df = pd.DataFrame(data, columns=["x", "y"])

sns.jointplot(x="x", y="y", data=df, kind='reg')
           
Python绘图总结(seaborn篇)之数据分布
#  kind="kde" 线条趋势
sns.jointplot(x="x", y="y", data=df, kind="kde")
           
Python绘图总结(seaborn篇)之数据分布
#  kind="kde" 六角形
x, y = np.random.multivariate_normal(mean, cov, ).T
with sns.axes_style("white"):
    sns.jointplot(x=x, y=y, kind="hex", color="k")
           
Python绘图总结(seaborn篇)之数据分布
g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
g.plot_joint(plt.scatter, c="w", s=, linewidth=, marker="+")
g.ax_joint.collections[].set_alpha()
g.set_axis_labels("X轴", "Y轴")
           
Python绘图总结(seaborn篇)之数据分布

5、pairplot() 成对关系

# https://github.com/mwaskom/seaborn-data 数据地址
iris = sns.load_dataset("iris")
sns.pairplot(iris)
           
Python绘图总结(seaborn篇)之数据分布
g = sns.pairplot(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=)
           
Python绘图总结(seaborn篇)之数据分布

继续阅读