longgb246的博客

Seaborn-03-数据分布图

基本

1
2
3
4
5
6
7
#-*- coding:utf-8 -*-
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats, integrate
import seaborn as sns

1、快速查看分布

distplot

1
2
3
x = np.random.randint(0,10,100)
sns.distplot(x, color="b", bins=10, rug=True)
sns.distplot(x, hist=False)

03_01.png

2、画单变量图

1
2
3
4
5
6
7
8
9
10
11
12
13
x = np.random.normal(0, 1, size=30)
bandwidth = 1.06 * x.std() * x.size ** (-1 / 5.) # 带宽计算公式
support = np.linspace(-4, 4, 200)
kernels = []
for x_i in x:
kernel = stats.norm(x_i, bandwidth).pdf(support)
kernels.append(kernel)
plt.plot(support, kernel, color="#C55458")
sns.rugplot(x, color=".2", linewidth=3)
density = np.sum(kernels, axis=0)
density /= integrate.trapz(density, support)
plt.plot(support, density)

03_02.png

1
sns.kdeplot(x, shade=True)

03_03.png

1
2
3
4
sns.kdeplot(x)
sns.kdeplot(x, bw=.2, label="bw: 0.2")
sns.kdeplot(x, bw=2, label="bw: 2")
plt.legend()

03_04.png

1
2
3
4
5
x = np.random.gamma(6, size=200)
sns.distplot(x)
sns.distplot(x, label='kde', hist=False)
sns.distplot(x, kde=False, fit=stats.gamma, label='fit-gamma', hist=False)
plt.legend()

03_05.png

3、画二元变量分布图

1
2
3
mean, cov = [0, 1], [[1, .5], [.5, 1]]
data = np.random.multivariate_normal(mean, cov, 200)
df = pd.DataFrame(data, columns=["x", "y"])

(1)散点图

1
sns.jointplot(x="x", y="y", data=df, stat_func=stats.pearsonr)

03_06.png

(2)六边图

1
2
3
4
data2 = np.random.multivariate_normal(mean, cov, 1000)
df2 = pd.DataFrame(data2, columns=["x", "y"])
with sns.axes_style("white"):
sns.jointplot(x=df2["x"], y=df2["y"], kind="hex", color="k")

03_061.png

(3)相交的 KDE 图

1
sns.jointplot(x="x", y="y", data=df2, kind="kde")

03_07.png

(4)地毯图的 KDE 图

1
2
3
4
f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df2.x, df2.y, ax=ax)
sns.rugplot(df2.x, color="#55A868", ax=ax)
sns.rugplot(df2.y, vertical=True, ax=ax, color="#4C72B0")

03_08.png

(5)星云图

1
2
3
f2, ax = plt.subplots(figsize=(6, 6))
cmap = sns.cubehelix_palette(as_cmap=True, dark=0, light=1, reverse=True)
sns.kdeplot(df2.x, df2.y, cmap=cmap, n_levels=60, shade=True)

03_09.png

(6)加入+图

1
2
3
4
g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="#988CBE")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("$X$", "$Y$")

03_10.png

(7)画出两两变量散点图

1
2
iris = sns.load_dataset("iris")
sns.pairplot(iris)

03_11.png

(8)画联合核函数

1
2
3
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=6)

03_12.png

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