Gradient fill beneath line chart using matplotlib?

后端 未结 1 1550
后悔当初
后悔当初 2021-01-22 06:50

I\'m trying to product a line chart with a gradient fill beneath the line. I have searched for hours online for a solution, but none of them deal specifically with what I\'m loo

相关标签:
1条回答
  • 2021-01-22 07:26

    There is actually a fairly nice answer to this at this SO question, and the following borrows the main idea, but I've substituted a call to imshow rather than contourf because I think it looks smoother. I borrow the key element, which is to place the gradient over the whole image and then 'erase' above the data using fill_between.

    import numpy as np
    import matplotlib.pyplot as plt
    import datetime
    import matplotlib.dates as mdates
    
    # Fake data using dates as requested
    xdata = np.array([datetime.datetime.today()+
                     datetime.timedelta(days=1)*i for i in range(15)])
    ydata = np.cumsum(np.random.uniform(size=len(xdata)))
    xlims = mdates.date2num([xdata[0], xdata[-1]])
    
    # Construct an image linearly increasing in y
    xv, yv = np.meshgrid(np.linspace(0,1,50), np.linspace(0,1,50))
    zv = yv
    
    # Draw the image over the whole plot area
    fig, ax = plt.subplots(figsize=(5,3))
    ax.imshow(zv, cmap='YlGnBu_r', origin='lower',
              extent=[xlims[0], xlims[1], ydata.min(), ydata.max()])
    
    # Erase above the data by filling with white
    ax.fill_between(xdata, ydata, ydata.max(), color='w')
    
    # Make the line plot over the top
    ax.plot(xdata, ydata, 'b-', linewidth=2)
    
    ax.set_ylim(ydata.min(), ydata.max())
    fig.autofmt_xdate()
    
    plt.show()
    

    This gives me this plot:

    smooth gradient fill plot

    0 讨论(0)
提交回复
热议问题