Home > database >  how to set plt.xlimit with date and time
how to set plt.xlimit with date and time

Time:05-07

I can only set the x axis limit to a certain date, but not with hours, minutes seconds. My code looks like this:

plt.figure()
plt.plot(data.date,sig,'b-')
plt.xlim([datetime.date(2022,4,27),datetime.date(2022,4,29)])
plt.ylim()

And my data frame looks like this:

                         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

I searched on the internet but I can only see examples of this xlimit with only a date, not with time. Does anyone know how I can add the time with it. for example the x limit should start at: '2022-04-27 11:07:39.721'

Kind regards,

Simon

CodePudding user response:

Turned string time into dtype='datetime64[ms]'. Then I created a variable 'f' for the desired time formatting.

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()

enter image description here

CodePudding user response:

I found the answer!

It should be datetime.datetime instead of datetime.date.

Example:

datetime.datetime(2022,4,27,12,1,1)
  • Related