Search code examples
pythonpython-3.xmatplotlibplotshading

Variable length shading in matplotlib using `fill_between`


I'm trying to generate a variable length shading for the plot. Right now, I only have fixed length shading from the actual line.

a    = np.linspace(1, 10)
loga = np.log(a)

_, ax = plt.subplots()

ax.plot(a, loga, lw=3, color='#27AE60', alpha=1)
ax.fill_between(a, loga+0.2, loga-0.2, color='#539caf', alpha=0.1)

ax.set_title("log plot")
plt.legend(["natural log"], loc="upper left")

The corresponding plot is:

log plot

However, I'd like to get a plot like the one in below figure. src: MSc-thesis

variable-length-shading

How can I modify my code to generate such a variable length shading? I mean the area to be shaded behind the line should increase as we go from left to right (i.e. as values in x-axis increases). I would be grateful for any help. Merry Xmas!


Solution

  • The answer is extremely obvious. The arguments of fill_between are the x-values, the y-values of the top edge of the fill area, and those of the bottom edge. Modifying those two will change the shading area:

    import matplotlib.pyplot as plt
    import numpy as np
    
    a    = np.linspace(1, 10)
    loga = np.log(a)
    
    _, ax = plt.subplots()
    
    ax.plot(a, loga, lw=3, color='#27AE60', alpha=1)
    ax.fill_between(a, loga+np.linspace(0,1,a.size), loga-np.linspace(0,1,a.size), color='#539caf', alpha=0.1)
    
    ax.set_title("log plot")
    plt.legend(["natural log"], loc="upper left")
    
    plt.show()
    plt.savefig('so.png')
    

    enter image description here

    Now, as to how to define these bounds... Of course this depends of the meaning you want these lines to have (i.e. your data). This is really problem specific, of which you mentioned nothing. (And is probably not about programming, so off-site).