当xaxis是timedelta时,在matplotlib中设置xlim

时间:2017-12-05 01:03:56

标签: python python-2.7 pandas matplotlib

当我使用timedelta时,设置xlim时遇到一些问题。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime

fig1 = plt.figure(figsize=(20,10))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})
df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

ax1.xaxis.set_major_formatter(DateFormatter('%M'))


ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])


ax1.plot_date(df['deltaTime'], df['length'], marker='o', markersize=5, linestyle='-')

plt.show() 

这条线似乎不起作用:

ax1.set_xlim([datetime.time(0,0,0), datetime.time(1,0,0)])

当我使用pandas timedelta时,是否有类似的东西可以用来设置限制?

1 个答案:

答案 0 :(得分:1)

matplotlib plot_date使用x和y作为日期时间对象,而不是timedelta(持续时间)对象。您可以将timedelta对象转换为datetime对象,如下所示(通过添加timedelta的日期对象)。希望这是你想要的。

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import datetime


fig1 = plt.figure(figsize=(4,4))
ax1 = fig1.add_subplot(111)

df = pd.DataFrame({'deltaTime': [0, 10, 20, 30], 'length': [0.002, 0.005, 0.004, 0.003]})

df['deltaTime'] = pd.to_timedelta(df['deltaTime'], unit='m')

df['start_date'] =  pd.Timestamp('20171204')+ df['deltaTime']
print df['start_date']

ax1.plot_date(df['start_date'], df['length'], marker='o', markersize=5, linestyle='-')                            
ax1.xaxis.set_major_formatter(DateFormatter('%M'))

ax1.set_xlim(['20171204 00:10:00', '20171204 00:30:00'])

plt.show()

结果

0   2017-12-04 00:00:00
1   2017-12-04 00:10:00
2   2017-12-04 00:20:00
3   2017-12-04 00:30:00
Name: start_date, dtype: datetime64[ns]

enter image description here