【发布时间】:2012-11-05 11:52:18
【问题描述】:
我正在尝试从使用 pandas 创建的时间序列图中将绘图的 xlimits 作为 python 日期时间对象。使用ax.get_xlim() 将轴限制返回为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)
返回:
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
根据pandas timeseries docs,pandas 使用 numpy.datetime64 dtype。我正在使用熊猫版本“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)
【问题讨论】:
标签: matplotlib pandas