python axes get,从熊猫时间序列图中的Axes.get_xlim()获取可用日期

I'm trying to get the xlimits of a plot as a python datetime object from a time series plot created with pandas. Using ax.get_xlim() returns the axis limits as a numpy.float64, and I can't figure out how to convert the numbers to a usable datetime.

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)

which returns:

262968.0 () to 272967.0 ()

Using matplotlib: 0720-12-25 00:00:00+00:00

Using datetime: 1970-01-03 19:02:48

According to the pandas timeseries docs, pandas uses the numpy.datetime64 dtype. I'm using pandas version '0.9.0'.

I am using get_xlim() instead directly accessing the pandas series because I am using the xlim_changed callback to do other things when the user moves around in the plot area.

Hack to get usable values

For the above example, the limits are returned in hours since the Epoch. So I can convert to seconds since the Epoch and use time.gmtime() to get somewhere usable, but this still doesn't feel right.

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)

解决方案# 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值