在matplotlib图中,可以突出显示特定的x值范围吗?

问题描述:

我正在可视化一个项目的历史库存数据,我想突出显示滴的区域.例如,当股票出现大幅缩水时,我想用红色区域突出显示它.

I'm making a visualization of historical stock data for a project, and I'd like to highlight regions of drops. For instance, when the stock is experiencing significant drawdown, I would like to highlight it with a red region.

我可以自动执行此操作,还是必须绘制矩形或其他内容?

Can I do this automatically, or will I have to draw a rectangle or something?

看看 axvspan (和axhspan突出显示y轴的区域).

Have a look at axvspan (and axhspan for highlighting a region of the y-axis).

import matplotlib.pyplot as plt

plt.plot(range(10))
plt.axvspan(3, 6, color='red', alpha=0.5)
plt.show()

如果您使用日期,则需要将x的最小值和最大值转换为matplotlib日期.将matplotlib.dates.date2num用于datetime对象,或将matplotlib.dates.datestr2num用于各种字符串时间戳.

If you're using dates, then you'll need to convert your min and max x values to matplotlib dates. Use matplotlib.dates.date2num for datetime objects or matplotlib.dates.datestr2num for various string timestamps.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

t = mdates.drange(dt.datetime(2011, 10, 15), dt.datetime(2011, 11, 27),
                  dt.timedelta(hours=2))
y = np.sin(t)

fig, ax = plt.subplots()
ax.plot_date(t, y, 'b-')
ax.axvspan(*mdates.datestr2num(['10/27/2011', '11/2/2011']), color='red', alpha=0.5)
fig.autofmt_xdate()
plt.show()