我想显示两个时间序列,以及它们的变化率相互重叠的时间段。我使用下面的代码,但是fill_between无法完全填充两条曲线之间的区域。我不知道为什么

结果图像:



plt.figure(figsize=(18,12))
ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot_date(data.index, data.Net,'g-', label='Net')
ax1.plot_date(data.index, data.HS300_NET,'r-', label='HS300_Net')
ax1.fill_between(data.index, data.Net, data.HS300_NET,
             where=(data.Net.pct_change() < data.HS300_NET.pct_change()),
             facecolor='g', alpha=0.5)
ax1.fill_between(data.index, data.Net, data.HS300_NET,
             where=(data.Net.pct_change() > data.HS300_NET.pct_change()),
             facecolor='r', alpha=0.5)

plt.legend()
plt.show()

最佳答案

尝试将interpolate=True添加到fill_between调用。

请参见example from official doc here

相关代码是

# now fill between y1 and y2 where a logical condition is met.  Note
# this is different than calling
#   fill_between(x[where], y1[where],y2[where]
# because of edge effects over multiple contiguous regions.
fig, (ax, ax1) = plt.subplots(2, 1, sharex=True)
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='green', interpolate=True)
ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
ax.set_title('fill between where')

关于python - pyplot根据两条曲线的变化率填充,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46029862/

10-13 06:43