Matplotlib 将实际日期添加到缩进图的X轴

Matplotlib 将实际日期添加到缩进图的X轴,matplotlib,timestamp,Matplotlib,Timestamp,我试图将时间戳/实际日期合并到缩图的X轴上。这段代码是从我之前看到的一篇文章中得到的 n = 1000 xs = np.random.randn(n).cumsum() i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period j = np.argmax(xs[:i]) # start of period plt.plot(xs) plt.plot([i, j], [xs[i], xs[j]], 'o', color='

我试图将时间戳/实际日期合并到缩图的X轴上。这段代码是从我之前看到的一篇文章中得到的

n = 1000
xs = np.random.randn(n).cumsum()
i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period
j = np.argmax(xs[:i]) # start of period

plt.plot(xs)
plt.plot([i, j], [xs[i], xs[j]], 'o', color='Red', markersize=10)

问题是这段代码的输入必须是NumPy数组类型。但在现实中,当你看到一个下降,你可能也希望看到它在一个实时的框架。我如何合并或可能只是添加整个实验期的开始和结束日期(而不仅仅是提款的开始和结束)?谢谢大家!

您可以使用此代码作为起点:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
plt.close()

# period n
n = 100
xs = np.random.randn(n).cumsum()
i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period
j = np.argmax(xs[:i]) # start of period

# start date and populating period n with dates
now = dt.datetime.now()
then = now + dt.timedelta(days=n)
days = mdates.drange(now, then, dt.timedelta(days=1))

# actual plot
plt.plot(days, xs, color="blue")
plt.plot([days[i], days[j]], [xs[i], xs[j]], 'o', color='Red', markersize=10)

# point labels
plt.annotate("end", (days[i], xs[i]))
plt.annotate("start", (days[j], xs[j]))

# vertical lines
plt.axvline(x=days[i], color="black")
plt.axvline(x=days[j], color="black")

# sets x-axis up for dates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=10))
plt.gcf().autofmt_xdate()
这使得:


您可以在
.annotate()
中修改点标签以表示该特定日期。通过将变量
now
更改为特定的日期时间,可以设置开始日期。更改
interval=10
值以选择x轴日期上的XTICK频率。

因此您想在两个标记处添加一个带有日期的标签?不仅如此,更重要的是,整个事情的开始和结束,整个回溯测试周期,这样当您看到它时,您就会明白“哦,从2015年到2020年(从开始到结束)的五年中,最大提款期从2016年5月开始,到2016年9月结束。可以说,基本上是里程碑事件的时间/日期。谢谢!这太完美了!但有一件事:你会如何规划一系列指定的日期呢?在你给出的这个例子中,日期只是一天一天地过去,而实际上你只有工作日的股票价格。我一直在尝试设置“日期”的方式,它等于熊猫系列的索引。你可以做的是寻找已经有日期的数据并将其用作数据帧。或者,您可以从所有日期列表中删除不想要的日期。如果已经解决了您的原始问题,请接受答案。:)谢谢你的提示!我对答案投了“赞成票”。这不算“批准”或“接受”吗?这就是答案。“检查”我有!