matplotlib 当xaxis为timedelta时,设置xlim

mbskvtky  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(111)

我在使用时间增量时设置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时,是否有类似的东西可以用来设置我的限制?

zed5wv10

zed5wv101#

matplotlib plot_date接受的x和y是datetime对象,而不是timedelta(duration)对象。你可以将timedelta对象转换为datetime对象,如下所示(通过添加一个带有timedelta的date对象)。您正在寻找的页面不存在。

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]

相关问题