Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python plot stem with datetime base

I wish to plot a stem with matplotlib using datetime base. but it seems error happen: Sample code:

import matplotlib.pyplot as plt
from dateutil import parser

x = parser.parse("2013-9-28 11:00:00")
y = 100

x1 = parser.parse("2013-9-28 12:00:00")
y1 = 200

plt.stem([x,x1],[y,y1],"*-")

The error message:

    318 
    319     """
--> 320     return array(a, dtype, copy=False, order=order)
    321 
    322 def asanyarray(a, dtype=None, order=None):

TypeError: float() argument must be a string or a number
like image 608
lucky1928 Avatar asked Nov 20 '25 14:11

lucky1928


2 Answers

It seems that stem x axis only admits floats, so you can convert your dates to timestamp (float) and then plotting. For showing the date on the axis use .xticks(). Here is an example:

import numpy as np
import matplotlib.pyplot as plt
from time import mktime
from datetime import datetime

ticks = [ "2013-9-28 11:00:00.234", "2013-9-28 11:10:00.123", "2013-9-28 11:40:00.654", "2013-9-28 11:50:00.341", "2013-9-28 12:00:00.773"]
y = np.array([10, 12, 9, 15, 11])
x = [mktime(datetime.strptime(i, "%Y-%m-%d %H:%M:%S.%f").timetuple()) for i in ticks]

plt.stem(x,y)
plt.xticks(x, ticks)
plt.show()

enter image description here

like image 127
jabaldonedo Avatar answered Nov 22 '25 05:11

jabaldonedo


One improve for above answer to support milliseconds.

import numpy as np
import matplotlib.pyplot as plt
from time import mktime
from datetime import datetime

def main():
    ticks = [ "2013-9-28 11:00:00.234",
             "2013-9-28 11:00:00.334",
             "2013-9-28 11:00:00.434",
             "2013-9-28 11:00:00.534",
             "2013-9-28 11:00:00.634"]
    y = np.array([10, 12, 9, 15, 11])

    fig = plt.figure(figsize=(4,3))
    ax = fig.add_subplot(1,1,1)
    dtlst = str2dt(ticks)
    ax.stem(dt2msec(dtlst),y)
    bins = 5
    dtlst = list(linspace(dtlst[0],dtlst[-1],bins))
    ax.set_xticks(dt2msec(dtlst))
    ax.set_xticklabels(dt2str(dtlst),rotation=15,ha='right')
    ax.yaxis.grid(True)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['top'].set_visible(False)

    plt.show()    
    return

def str2dt(strlst):
    year = ""#"2014-"
    dtlst = [datetime.strptime(year+i, "%Y-%m-%d %H:%M:%S.%f") for i in strlst]
    return dtlst

def dt2msec(dtlst):
    floatlst = [mktime(dt.timetuple())*1000+dt.microsecond/1000 for dt in dtlst]
    return floatlst

def dt2str(dtlst):
    dtstr = [dt.strftime("%Y-%m-%d %H:%M:%S.%f %Z%z") for dt in dtlst]
    return dtstr

def msec2dt(msecs):
    dtlst = [datetime.fromtimestamp(msecs/1000.0).replace(microsecond=msecs%1000*1000) for msecs in floatlst]
    return dtlst

def linspace(start, end, bins):
    delta = (end - start)/bins
    x = start
    while x <= end:
        yield x
        x = x + delta
    return

#-----------------------------------------#
if __name__ == "__main__":
    main()
#-----------------------------------------#

Output:

enter image description here


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!