matplotlib plot_date()在指定日期添加垂直线 [英] matplotlib plot_date() add vertical line at specified date
问题描述
我的数据存储为pandas数据框。我使用matplotlib中的plot_date()函数创建了日期(对象格式)与百分位数(int64格式)的图表,并希望在预先指定的日期添加一些垂直线。
My data is stored as a pandas dataframe. I have created a chart of date (object format) vs. percentile (int64 format) using the plot_date() function in matplotlib and would like to add some vertical lines at pre-specified dates.
我设法在预定日期添加了点标记,但是似乎找不到找到使它们成为垂直线的方法。
I have managed to add point markers at the pre-specified dates, but can't seem to find a way to make them into vertical lines.
我在SO / SE上找到了有关如何向plot()添加垂直线的各种答案,但是在将数据转换为plot()可以使用的格式时遇到了麻烦,因此为什么我要使用plot_date()。
I've found various answers on SO/SE about how to add vertical lines to a plot(), but am having trouble converting my data to a format that can be used by plot(), hence why I have used plot_date().
示例数据:
date percentile
2012-05-30 3
2014-11-25 60
2012-06-15 38
2013-07-18 16
我绘制图表的代码如下:
My code to plot the chart is as below:
x_data = data["date"]
y_data = data["percentile"]
plt.figure()
plt.plot()
#create a scatter chart of dates vs. percentile
plt.plot_date(x = x_data, y = y_data)
#now add a marker at prespecified dates - ideally this would be a vertical line
plt.plot_date(x = '2012-09-21', y = 0)
plt.savefig("percentile_plot.png")
plt.close()
不幸的是,我无法提供当前输出的图像作为代码在没有网络访问权限的终端上。
Unfortunately I can't provide an image of the current output as the code is on a terminal with no web access.
任何帮助都将不胜感激-也是在我问这个问题的方式上,因为我是SO的新手/ SE。
Any help is greatly appreciated - also in terms of how I've asked the question as I am quite new to SO / SE.
谢谢。
推荐答案
在MatPlotLib 1.4.3中这项工作:
In MatPlotLib 1.4.3 this works:
import datetime as dt
plt.axvline(dt.datetime(2012, 9, 21))
传递字符串式日期( 2012-09- 21
)不起作用,因为MPL不知道这是一个日期。无论您使用什么代码加载文件,都可能会在字符串中隐式创建 datetime
对象,这就是为什么绘图调用起作用的原因。
Passing a string-style date (2012-09-21
) doesn't work because MPL doesn't know this is a date. Whatever code you are using to load your file is probably implicitly creating datetime
objects out of your strings, which is why the plot call works.
此外,在MPL 1.4.3中,我不需要调用 plt.plot_date(data ['date'],...)
只要 data ['date'] plt.plot(data ['date'],...)
对我有用code>列是 datetime
对象的列。
Also, in MPL 1.4.3, I did not need to call plt.plot_date(data['date'], ...)
, simply calling plt.plot(data['date'], ...)
worked for me as long as the data['date']
column is a column of datetime
objects.
祝你好运。
这篇关于matplotlib plot_date()在指定日期添加垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!