0

I have a time serie determined by sec.nsec (unix time?) where a signal is either 0 or 1 and I want to plot it to have a square signal. Currently I have the following code:

from matplotlib.pyplot import *

time = ['1633093403.754783918', '1633093403.755350983', '1633093403.760918965', '1633093403.761298577', '1633093403.761340378', '1633093403.761907443']
data = [1, 0, 1, 0, 1, 0] 

plot(time, data)
show()

This plots: enter image description here

Is there any conversion needed for the time before plotting? I cannot have date:time as this points might have ns to ms between them

Thank you.

EDIT: The values of the list for time are strings

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31
aripod
  • 55
  • 1
  • 14
  • adding `drawstyle='steps-pre'` to plot worked. However, is that the correct way to plot it? – aripod Oct 01 '21 at 14:15
  • `date = np.datetime64(time, 's')` should give you numpy datetime64 array and Matplotlib should give you better looking ticks. If you don't care about dates, then you could also just subtract the start of the day or hour or something. – Jody Klymak Oct 01 '21 at 14:26
  • The thing is that I am not getting the time from a python script but plotting from a file. However, just to test your suggestion, I tried `date = np.datetime64(time[0], 's')` but that throw the error `Could not convert object to NumPy datetime`. Still, using `drawstyle='steps-pre'` worked – aripod Oct 01 '21 at 14:32
  • Sorry, you need to convert to int before passing to datetime64. So maybe: `date = np.datetime64(int(1e6*time[0]), 'us')` – Jody Klymak Oct 02 '21 at 09:49
  • I've just edited the question. The list `time` is composed by strings (sec.nsec). What I am thinking is that I should convert the sec and nsec individually to int, then convert the sec to nsec and and those two numbers together.... – aripod Oct 07 '21 at 08:16

1 Answers1

0

To convert unix timestamp strings to datetime64 you need to fist convert to float, and then convert to datetime64 with the correct units:

time = ['1633093403.754783918', '1633093403.755350983', '1633093403.760918965', '1633093403.761298577', '1633093403.761340378', '1633093403.761907443']
time = (np.asarray(time).astype(float)).astype('datetime64[s]')
print(time.dtype)
print(time)

yields:

datetime64[s]
['2021-10-01T13:03:23' '2021-10-01T13:03:23' '2021-10-01T13:03:23'

Note the nanoseconds have been stripped. If you want to keep those...

time = (np.asarray(time).astype(float)*1e9).astype('datetime64[ns]')

yields:

datetime64[ns]
['2021-10-01T13:03:23.754783744' '2021-10-01T13:03:23.755351040'
 '2021-10-01T13:03:23.760918784' '2021-10-01T13:03:23.761298688'
 '2021-10-01T13:03:23.761340416' '2021-10-01T13:03:23.761907456']

This all works because datetime64 has the same "epoch" or zero as unix timestamps (1970-01-01T00:00:00.000000)

Once you do this conversion, plotting should work fine.

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31