在 matplotlib 图中,我可以突出显示特定的 x 值范围吗? [英] In a matplotlib plot, can I highlight specific x-value ranges?

查看:33
本文介绍了在 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(以及用于突出 y 轴区域的 axhspan).

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

这篇关于在 matplotlib 图中,我可以突出显示特定的 x 值范围吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆