Python-matplotlib 曲线下方填色的概率(高斯)分布图
这里直接把代码放上来方便日后再次使用,主要是曲线下方填色比较好看
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st
def plot_gaussian_distribution(means, stds, n_basesample=1000, alpha_line=0.5, alpha_fill=0.6):
"""
Args:
means: list of mean
stds: list of standard deviation
n_basesample: num of sample
alpha_line: transparency of line
alpha_fill transparency of the filling
Returns:
"""
title_fontsize = 20
xlabel_fontsize = ylabel_fontsize = 15
plt.figure(figsize=(8, 6))
colors = ['r', 'g', 'purple', 'olive', 'gray', 'gold', 'teal', 'b',
'crimson', 'orange', 'deepskyblue', 'orchid']
assert len(means) == len(stds)
assert len(colors) >= len(means)
plt.style.use('seaborn')
for i in range(len(means)):
s = np.random.normal(means[i], stds[i], n_basesample)
s_fit = np.linspace(s.min(), s.max())
plt.plot(s_fit, st.norm(means[i], stds[i]).pdf(s_fit), lw=1, c=colors[i], alpha=alpha_line)
plt.fill_between(x=s_fit, y1=0, y2=st.norm(means[i], stds[i]).pdf(s_fit), facecolor=colors[i], alpha=alpha_fill)
plt.title('PDF or something else',fontsize=title_fontsize)
plt.xlabel("xlabel", fontsize=xlabel_fontsize)
plt.ylabel("ylabel", fontsize=ylabel_fontsize)
plt.show()
if __name__=='__main__':
means = [2, 4, 5]
stds = [0.8, 1, 0.5]
plot_gaussian_distribution(means, stds)
这里展示的是高斯分布图,函数只用输入均值,标准差的数组就可以绘制出图片。填色代码主要是这一句:
plt.fill_between(x=s_fit, y1=0, y2=st.norm(means[i], stds[i]).pdf(s_fit), facecolor=colors[i], alpha=alpha_fill)
值得注意的,这里填色和曲线颜色的深浅由alpha 这一项控制,值越大颜色越深。
颜色可以参考下图:
|