直方图#

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
# matplotlib加入中文支持
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

基本直方图#

x = np.random.randn(1000)

bins:📊条数

alpha:透明度

color:颜色

density:面积是否归为1

plt.hist(x, bins=20, alpha=0.5, color='steelblue', density=False)
# axvline插入竖线 
plt.axvline(np.mean(x), c='red')
plt.xlabel("值")
plt.ylabel("数量")
plt.title("正态分布抽样")
plt.show()
../_images/bf1712d745838a42adcb13002e3002eedaa429ba1c19af5bb6d5271f4f131425.png

多个hist组合#

x1 = np.random.normal(0, 1, 1000)
x2 = np.random.normal(3, 2, 1000)
x3 = np.random.normal(-2, 1.5, 1000)

# 由kwargs表示hist参数,不必配置color,会自动区分开
kwargs = dict(bins=40, alpha=0.3, density=True)

plt.hist(x1, **kwargs, label="x1")
plt.hist(x2, **kwargs, label="x2")
plt.hist(x3, **kwargs, label="x3")
plt.legend()
plt.show()
../_images/1667d3e6bb9b5b1a828a5c49236273b54d4d4cce4b6e7390d35f3f263badd72f.png

各种plt风格#

plt.style.available
['Solarize_Light2',
 '_classic_test_patch',
 '_mpl-gallery',
 '_mpl-gallery-nogrid',
 'bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark',
 'seaborn-dark-palette',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'tableau-colorblind10']
with plt.style.context("ggplot"):
    plt.hist(x, bins=20, alpha=0.5, density=False, color='steelblue')
../_images/af047462bd04f0f563795632953b3506eefefbf8dca8646e2dc6145d5c09c192.png

seaborn直方图及kde#

import seaborn as sns

displot融合了直方图和kde,它没有alpha和density参数

sns.distplot(x, bins=20, color='green')
plt.title("核密度估计(kde)")
plt.show()
../_images/6f0e0883a9b19f0f66bbfb9152d21f4176a120c2957a56ddf99322c741a8c61b.png

kdeplot只展示kde

sns.kdeplot(x1*x2, color='red')
plt.show()
../_images/ae2ad55f35c236144c1aaa5bf5379919aa3a3f501efa1903d70e6e13b29d18ac.png