Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot timedelta as value with matplotlib

I am trying to plot a duration in seconds with respect to some iteration values. I compute the duration values by substracting two datetime values. Then, I would like to plot these results in a very simple way using existing tools.

My code is the following but it doesn't work yet:

#!/usr/bin/env python

import datetime
import matplotlib.pyplot as plt
from numpy import arange

it = arange(10)
durations = [datetime.timedelta(hours=h+30) for h in it]

plt.plot(it, durations)

plt.show()

I got the following error:

TypeError: float() argument must be a string or a number

I know that I can make it work by using datetime instead of timedelta but my goal is to plot duration in hours (around 40 hours) so the rendering is not good.

like image 255
Sigmun Avatar asked Nov 23 '16 12:11

Sigmun


People also ask

How do I plot time series data in Matplotlib?

In X-axis we should have a variable of DateTime. In Y-axis we can have the variable which we want to analyze with respect to time. plt. plot() method is used to plot the graph in matplotlib.

What does Timedelta return Python?

TimeDelta to Seconds A time delta object instance has a method called total_seconds() to calculate the total number of seconds in duration. This returns a floating-point value of total seconds, up to microseconds accuracy. But for larger intervals like 270 years, this method loses the microsecond accuracy.

How do I convert Timedelta to hours in Python?

How to convert a timedelta to hours. We can follow the same logic to convert a timedelta to hours. Instead of dividing the total_seconds() by the number of seconds in a minute, or dividing the timedelta object by timedelta(minutes=1) , we do it for hour.


1 Answers

That's because there is no defined conversion for timedelta to float. You can use:

durations = [datetime.timedelta(hours=h+30).total_seconds()/3600.0 for h in it]

to transform the duration to floating point hours. Look at how to format your tick labels if you want the nice hour notation on your plot. You can convert the hour (float) to a nicely formatted hour string.

(EDIT: changed .total_seconds to .total_seconds()

like image 93
kabanus Avatar answered Sep 29 '22 05:09

kabanus