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

1.2k views Asked by At

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)

plot with shaded representation of uncertainty

0

There are 0 answers