3

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

Gavin Ridley
  • 371
  • 3
  • 15
  • That looks pretty good already, especially as it's easy to adapt to different distributions. If you put it in a function with sensible defaults (distribution=Gaussian, numsigma, numsteps) it will be as easy to use as fill_between. – cphlewis Sep 02 '17 at 18:50
  • @cphlewis thanks, I was mainly just wondering if there is some way to do `alpha= f(y)` and have alpha vary over the shaded region automatically rather than this sort of brute force approach. – Gavin Ridley Sep 02 '17 at 22:16
  • You mean `alpha=f(y)` replacing the whole final loop? Yes, you could rewrite what you have that way. I think `f` has to do just as much clunky work to define the shading and the envelope. I'd sketch out what functions would need what parameters to pick the most elegant version. – cphlewis Sep 04 '17 at 07:23

0 Answers0