[英]set the xlim in matplotlib when xaxis is timedelta
使用xlim
时,设置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)])
使用熊猫timedelta时,是否可以使用类似的方法来设置限制?
matplotlib plot_date使用 x和y作为日期时间对象,而不是timedelta(持续时间)对象。 您可以将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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.