Search code examples
pythonmatplotlibareaenvelope

How to draw enveloping line with a shaded area which incorporates a large number of data points?


enter image description here

For the figure above, how can I draw an enveloping line with a shaded area, similar to the figure below?

enter image description here


Solution

  • Replicating your example is easy because it's possible to calculate the min and max at each x and fill between them. eg.

    import matplotlib.pyplot as plt
    import numpy as np
    
    #dummy data
    y = [range(20) + 3 * i for i in np.random.randn(3, 20)]
    x = list(range(20))
    
    #calculate the min and max series for each x
    min_ser = [min(i) for i in np.transpose(y)]
    max_ser = [max(i) for i in np.transpose(y)]
    
    #initial plot
    fig, axs = plt.subplots()
    axs.plot(x, x)
    for s in y:
        axs.scatter(x, s)
    
    #plot the min and max series over the top
    axs.fill_between(x, min_ser, max_ser, alpha=0.2)
    

    giving

    enter image description here

    For your displayed data, that might prove problematic because the series do not share x values in all cases. If that's the case then you need some statistical technique to smooth the series somehow. One option is to use a package like seaborn, which provides functions to handle all the details for you.