gpt4 book ai didi

python - 当xaxis为timedelta时设置xlim

转载 作者:行者123 更新时间:2023-12-01 02:23:51 25 4
gpt4 key购买 nike

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

最佳答案

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

关于python - 当xaxis为timedelta时设置xlim,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com