如何设置 plt.xlimit 日期和时间
how to set plt.xlimit with date and time
我只能设置x轴限制到某个日期,不能设置时分秒。我的代码如下所示:
plt.figure()
plt.plot(data.date,sig,'b-')
plt.xlim([datetime.date(2022,4,27),datetime.date(2022,4,29)])
plt.ylim()
我的数据框如下所示:
date x y z bat
0 2022-04-27 11:07:39.721 -0.875 -0.143 0.516 NaN
1 2022-04-27 11:08:04.721 -0.875 -0.143 0.516 NaN
2 2022-04-27 11:08:29.721 -0.875 -0.143 0.484 NaN
3 2022-04-27 11:08:54.721 -0.875 -0.143 0.484 NaN
4 2022-04-27 11:09:19.721 -0.875 -0.143 0.484 NaN
我在网上搜索过,但我只能看到这个 xlimit 的例子只有日期,没有时间。有谁知道我如何用它来增加时间。例如,x 限制应开始于:'2022-04-27 11:07:39.721'
亲切的问候,
西蒙
将字符串时间转换为 dtype='datetime64[ms]'。然后我为所需的时间格式创建了一个变量 'f'。
from matplotlib import dates
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
time_ = ['2022-04-27 11:07:39.721', '2022-04-27 11:08:04.721',
'2022-04-27 11:08:29.721', '2022-04-27 11:08:54.721', '2022-04-27 11:09:19.721']
#time_[0]---<class 'str'>
data = np.array(time_, dtype='datetime64[ms]')#type(data[0]---<class 'numpy.datetime64'>
val = [1, 1, 1, 1, 1]
f = dates.DateFormatter('%Y-%m-%d %H:%M:%S')
fig, ax = plt.subplots()
plt.plot(data, val)
plt.xlim(data[0], data[2])
#2022-04-27 11:07:39.721 by 2022-04-27 11:08:29.721
plt.ylim()
locator = matplotlib.ticker.LinearLocator(5)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(f)
fig.autofmt_xdate()
plt.show()
我找到答案了!
应该是datetime.datetime
而不是datetime.date
。
示例:
datetime.datetime(2022,4,27,12,1,1)
我只能设置x轴限制到某个日期,不能设置时分秒。我的代码如下所示:
plt.figure()
plt.plot(data.date,sig,'b-')
plt.xlim([datetime.date(2022,4,27),datetime.date(2022,4,29)])
plt.ylim()
我的数据框如下所示:
date x y z bat
0 2022-04-27 11:07:39.721 -0.875 -0.143 0.516 NaN
1 2022-04-27 11:08:04.721 -0.875 -0.143 0.516 NaN
2 2022-04-27 11:08:29.721 -0.875 -0.143 0.484 NaN
3 2022-04-27 11:08:54.721 -0.875 -0.143 0.484 NaN
4 2022-04-27 11:09:19.721 -0.875 -0.143 0.484 NaN
我在网上搜索过,但我只能看到这个 xlimit 的例子只有日期,没有时间。有谁知道我如何用它来增加时间。例如,x 限制应开始于:'2022-04-27 11:07:39.721'
亲切的问候,
西蒙
将字符串时间转换为 dtype='datetime64[ms]'。然后我为所需的时间格式创建了一个变量 'f'。
from matplotlib import dates
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
time_ = ['2022-04-27 11:07:39.721', '2022-04-27 11:08:04.721',
'2022-04-27 11:08:29.721', '2022-04-27 11:08:54.721', '2022-04-27 11:09:19.721']
#time_[0]---<class 'str'>
data = np.array(time_, dtype='datetime64[ms]')#type(data[0]---<class 'numpy.datetime64'>
val = [1, 1, 1, 1, 1]
f = dates.DateFormatter('%Y-%m-%d %H:%M:%S')
fig, ax = plt.subplots()
plt.plot(data, val)
plt.xlim(data[0], data[2])
#2022-04-27 11:07:39.721 by 2022-04-27 11:08:29.721
plt.ylim()
locator = matplotlib.ticker.LinearLocator(5)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(f)
fig.autofmt_xdate()
plt.show()
我找到答案了!
应该是datetime.datetime
而不是datetime.date
。
示例:
datetime.datetime(2022,4,27,12,1,1)