简体   繁体   中英

Plotting time on the x-axis with Python's matplotlib

I am reading in data from a text file which contains data in the format (date time; microVolts):

eg 07.03.2017 23:14:01,000; 279

And I wish to plot a graph using matplotlib by capturing only the time (x-axis) and plotting it against microVolts (y-axis). So far, I've managed to extract the time element from the string and convert it into datetime format (shown below).

I tried to append each value of time into x to plot, but the program just freezes and displays nothing.

Here is part of the code:

from datetime import datetime
import matplotlib.pyplot as plt


ecg = open(file2).readlines()

x = []
for line in range(len(ecg)):
    ecgtime = ecg[7:][line][:23]
    ecgtime = datetime.strptime(ecgtime, '%d.%m.%Y %H:%M:%S,%f')
    x.append(ecgtime.time())

I'm aware the datetime format is causing the issue but I can't figure out how to convert it into float/int as it says:

'invalid literal for float(): 23:14:01,000'

I have no reputation for comment than I have to answer.

datetime.datetime.time() converts to datetime.time object, you need float.
Could you try datetime.datetime.timestamp() ?

See last line:

from datetime import datetime
import matplotlib.pyplot as plt

ecg = open(file2).readlines()

x = []
for line in range(len(ecg)):
    ecgtime = ecg[7:][line][:23]
    ecgtime = datetime.strptime(ecgtime, '%d.%m.%Y %H:%M:%S,%f')
    x.append(ecgtime.timestamp())

EDIT: timestamp() is available sine Python 3.3. For Python 2 you can use

from time import mktime
...
    x.append(mktime(ecgtime.timetuple()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM