使用 matplotlib 在折线图下方进行渐变填充?

Gradient fill beneath line chart using matplotlib?

我正在尝试制作一个线下方具有渐变填充的折线图。我在网上搜索了几个小时的解决方案,但 none 中的解决方案专门针对我正在寻找的内容。

ma = average_rate(t[0], window=900, interval=60)
fig = Figure(figsize=(8.5, 1.5), dpi=100)
canvas = FigureCanvasAgg(fig)

col = '#4f81b3'
ax = fig.add_axes([0.076, 0.11, 0.88, 0.74])

dts, vals = zip(*ma)
ax.fill(dts, vals, color=col)
fig.savefig(b, format='png')

这将生成以下图表:

我曾尝试将颜色图、轮廓图、fill_between 等与我在网上找到的代码一起使用,但无法正常工作,我真的希望有人能为这个问题提供简单的解决方案。

在@Ajean的帮助下,我最新的代码如下:

    # dtseries contains a list of datetime.datetime values
    # yvalues contains a corresponding list of y-axis values
    # len(dtseries) == len(yvalues)

    import numpy as np

    # Need dpi for png generation
    fig = Figure(figsize=(8.5, 2), dpi=100)
    # Create axes directly on figure [left, bottom, width, height]
    ax = fig.add_axes([0.076, 0.11, 0.88, 0.74])

    xlims = mdates.date2num([dtseries[0], dtseries[-1]])

    # Construct an image linearly increasing in y
    xv, yv = np.meshgrid(np.linspace(0,1,50), np.linspace(0,1,50))
    zv = yv

    ax.imshow(zv, cmap='PuBu', origin='lower',
              extent=[xlims[0], xlims[1], min(yvalues), max(yvalues)])

    # Erase above the data by filling with white
    ax.fill_between(dtseries, yvalues, max(yvalues), color='w')

    # Make the line plot over the top
    colr = '#325272'
    ax.plot(dtseries, yvalues, color=colr, linewidth=0.5)

    ax.set_ylim(min(yvalues), max(yvalues))

    # Render chart as png to memory
    b = BytesIO()
    fig.savefig(b, format='png')
    return b.getvalue()

这是我得到的:

this SO 问题上实际上有一个相当不错的答案,下面借用了主要思想,但我用 imshow 而不是 contourf 因为我觉得这样看起来更流畅。我借用了关键元素,即在整个图像上放置渐变,然后使用 fill_between.

在数据上方 'erase'
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()

这给了我这个情节: