Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

showing milliseconds in matplotlib

I'm using matplotlib to plot data as a function of time in hh:mm:ss.ms format where ms is milliseconds. However, I don't see the milliseconds in the plot. Is it possible to add them as well?

dates = matplotlib.dates.datestr2num(x_values) # convert string dates to numbers
plt.plot_date(dates, y_values)  # doesn't show milliseconds
like image 961
Bob Avatar asked Jun 19 '12 19:06

Bob


People also ask

How do I show milliseconds in Python?

strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime object.

How to get datetime in milliseconds Python?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .


1 Answers


The problem here is that there is a class to format ticks, and plot_date sets that class to something that you don't want: an automatic formatter that never plots milliseconds.

In order to change this, you need to change from matplotlib.dates.AutoDateFormatter to your own formatter. matplotlib.dates.DateFormatter(fmt) creates a formatter with a datetime.strftime format string. I'm not sure how to get this to show milliseconds, but it will show microseconds, which I hope will work for you; it's just one extra zero, after all. Try this code:

dates = matplotlib.dates.datestr2num(x_values) # convert string dates to numbers
plt.plot_date(dates, y_values)  # doesn't show milliseconds by default.

# This changes the formatter.
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%H:%M:%S.%f"))

# Redraw the plot.
plt.draw()
like image 133
cge Avatar answered Oct 14 '22 13:10

cge