syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python Matplotlib how do I plot a time series?


When I want to plot data using Matplotlib the first thing I do is separate the x-values into a list and the y-values into a list.

Then the Matplotlib pyplot API is easy to use.

Usually the values are either integers or floats.

What if I want the x-values to correspond to a time dimension?

The answer is easy, just convert whatever x-values I have into a list of datetime objects.

To script the conversion, I need to understand how to build a Python-comprehension which is a feature similar to the .map() method in Ruby.

Let the syntax do the plotting:
$ cat eur_usd.csv
1241136000,1.325
1241136300,1.329
1241136600,1.320
1241136900,1.325
1241137200,1.327
1241137500,1.329
1241137800,1.323
1241138100,1.320
1241138400,1.326
1241138700,1.320


# plot_datetime.py import numpy as np eur_usd = np.loadtxt('eur_usd.csv', delimiter=',') import datetime d1970 = datetime.datetime.strptime( '1970-01-01', '%Y-%m-%d' ) # Python comprehension is like Ruby-enummerable.map() mydt = [d1970 + datetime.timedelta(seconds=int(utime)) for utime in eur_usd[:,0]] # I should get a list from above expression. import matplotlib.pyplot as plt plt.plot(mydt, eur_usd[:,1]) plt.show()
I should see something like this:


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me