【Python-matplotlib】曲线下方填色的概率(高斯)分布图

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:
    """
    # setting
    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)    # if not try to add color to 'colors'

    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这一项控制,值越大颜色越深。

颜色可以参考下图:
在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

quintus0505

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值