我试图从用熊猫创建的时间序列图中获取绘图的xlimits作为python datetime对象.使用ax.get_xlim()
将轴限制返回为a numpy.float64
,我无法弄清楚如何将数字转换为可用的日期时间.
import pandas
from matplotlib import dates
import matplotlib.pyplot as plt
from datetime import datetime
from numpy.random import randn
ts = pandas.Series(randn(10000), index=pandas.date_range('1/1/2000',
periods=10000, freq='H'))
ts.plot()
ax = plt.gca()
ax.set_xlim(datetime(2000,1,1))
d1, d2 = ax.get_xlim()
print "%s(%s) to %s(%s)" % (d1, type(d1), d2, type(d2))
print "Using matplotlib: %s" % dates.num2date(d1)
print "Using datetime: %s" % datetime.fromtimestamp(d1)
Run Code Online (Sandbox Code Playgroud)
返回:
262968.0 (<type 'numpy.float64'>) to 272967.0 (<type 'numpy.float64'>)
Using matplotlib: 0720-12-25 00:00:00+00:00
Using datetime: 1970-01-03 19:02:48
Run Code Online (Sandbox Code Playgroud)
根据pandas timeseries文档,pandas使用numpy.datetime64 dtype.我正在使用pandas版本'0.9.0'.
我使用的是get_xlim()
直接访问pandas系列,因为xlim_changed
当用户在绘图区域中移动时,我正在使用 回调来执行其他操作.
对于上面的示例,自Epoch以来,以小时为单位返回限制.因此,我可以转换为自大纪元以来的秒数,并且可以使用time.gmtime()
某个地方可用,但这仍然感觉不对.
In [66]: d1, d2 = ax.get_xlim()
In [67]: time.gmtime(d1*60*60)
Out[67]: time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=0)
Run Code Online (Sandbox Code Playgroud)
# First convert to pandas Period
period = pandas.tseries.period.Period(ordinal=int(d1), freq=ax.freq)
# Then convert to pandas timestamp
ts = period.to_timestamp()
# Then convert to date object
dt = ts.to_datetime()
Run Code Online (Sandbox Code Playgroud)
matplotlib.dates的当前行为:
datetime对象转换为浮点数,表示自0001-01-01 UTC以来的天数加1.例如,0001-01-01,06:00是1.25,而不是0.25.辅助函数date2num(),num2date()和drange()用于简化与datetime和numeric范围之间的转换.
pandas.tseries.converter.PandasAutoDateFormatter()似乎是以此为基础的,所以:
x = pandas.date_range(start='01/01/2000', end='01/02/2000')
plt.plot(x, x)
matplotlib.dates.num2date(plt.gca().get_xlim()[0])
Run Code Online (Sandbox Code Playgroud)
得到:
datetime.datetime(2000, 1, 1, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x7ff73a60f290>)
Run Code Online (Sandbox Code Playgroud)