如何使用matplotlib在两条直方图线之间进行颜色填充?

时间:2019-08-07 19:11:12

标签: matplotlib histogram

我有两个直方图(信号和背景),每个直方图都有上下不确定性范围。我想将每个直方图绘制为仅使用未填充的彩色边缘,然后绘制上,下不确定度直方图,并使用自己的未填充彩色边缘,然后将上,下直方图之间的区域填充为一种娱乐圈。如何实现?

这是我刚才的非常粗糙的代码(可以在Jupyter中使用):

import matplotlib.pyplot as plt
import numpy as np
from pylab import normal
import seaborn as sns
sns.set(context="paper", font="monospace")
import warnings
warnings.filterwarnings('ignore')

%matplotlib inline
plt.rcParams["figure.figsize"] = [8, 8]
plt.rc("text", usetex=True)
plt.rc("font", family="serif")

s    = normal(1, .2, 5000)
s_up = normal(1, .2, 5500)
s_dn = normal(1, .2, 4600)
b    = normal(2, .2, 2500)

ns, bins, patches = plt.hist(
    [s, s_up, s_dn, b],
    color=['r', 'g', 'g', 'b'],
    label=['signal nominal', 'signal upper bound', 'signal lower bound', 'background'],
    alpha=0.5,
    linewidth=1,
    histtype='stepfilled');
plt.setp(patches[0], edgecolor='r')
plt.setp(patches[1], edgecolor='b')
plt.legend();
plt.show();

1 个答案:

答案 0 :(得分:2)

类似的东西吗?

s    = normal(1, .2, 5000)
s_up = normal(1, .2, 5500)
s_dn = normal(1, .2, 4600)

bins = np.linspace(0., 2., 21)

n_up,b_up,p_up = plt.hist(s_up, bins=bins,  bottom=0, linewidth=1, histtype='stepfilled', facecolor='none', edgecolor='red', linestyle='--', label='signal upper bound')
n_dn,b_dn,p_dn = plt.hist(s_dn, bins=bins,  bottom=0, linewidth=1, histtype='stepfilled', facecolor='none', edgecolor='green', linestyle='--', label='signal lower bound')
n,b,p = plt.hist(s, bins=bins, bottom=0, linewidth=2, histtype='stepfilled', facecolor='none', edgecolor='k', label='signal nominal')
plt.bar(x=b_up[:-1], height=n_up-n_dn, bottom=n_dn, width=np.diff(b_up), align='edge', linewidth=0, color='red', alpha=0.25, zorder=-1, label='uncertainty band')
plt.legend()

enter image description here