使用matplotlib在折线图下面填充渐变?

时间:2015-01-14 20:09:07

标签: matplotlib

我正在尝试使用线下方的渐变填充来生成折线图。我已经在网上搜索了几个小时的解决方案,但没有一个专门处理我正在寻找的内容。

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')

这会生成以下图表:

我曾尝试使用colormaps,contourf,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()

这就是我得到的:

1 个答案:

答案 0 :(得分:1)

this SO问题上实际上有一个相当不错的答案,以下内容借用了主要想法,但我已经用imshow代替了contourf而不是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() 的数据上方。

{{1}}

这给了我这个情节:

smooth gradient fill plot