How to shade under curve in matplotlib, but with variable color alpha?

╄→尐↘猪︶ㄣ 提交于 2019-12-10 12:08:07

问题


I have some data points which are a function of one variable. I'd like to plot these, but there's associated uncertainty in each datum. Error bars would be OK, but I'd like to be able to visualize the way we expect the error to be distributed as well. For instance, a gaussian distribution with known width could be given.

I'm hoping that the alpha value of fill_between could be set according to the probability distribution, resulting in a plot like in this question about filling under a curve, , but instead shaded both above and below with alpha according to a gaussian.

I imagine there may be some way to hack fill_between to make this work, but I'm unable to figure it out so far. Here's what I have so far, can anyone do this more elegantly?

# example x data, y data, and uncertainties
def exampleFunc(x):
    return np.sin((x/1.5-3.0)**2)+1.0

xdata = np.linspace(0,10,100)
ydata = exampleFunc(xdata)

# define this data to be gaussian distributed with these standard 
# deviations
uncertainties = np.sqrt(ydata)

fig, ax = pl.subplots()


# plot the data centers on a line
ax.plot(xdata, ydata, 'b') # blue to stand out from shading

numsigma = 5 # how many standard deviations to go out
numsteps = 100 # how many steps to take in shading

# go to shade the uncertainties between, out to 4 sigma
for i in range(1,numsteps+1):
    top = ydata + uncertainties/numsteps*i*numsigma
    bottom = ydata - uncertainties/numsteps*i*numsigma
    ax.fill_between(xdata, bottom, top, color='r', 
        alpha=1.0/numsteps)

来源:https://stackoverflow.com/questions/46016782/how-to-shade-under-curve-in-matplotlib-but-with-variable-color-alpha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!