O'Reilly logo

matplotlib Plotting Cookbook by Alexandre Devert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Plotting curves from file data

As explained earlier, matplotlib only handles plotting. If you want to plot data stored in a file, you will have to use Python code to read the file and extract the data you need.

How to do it...

Let's assume that we have time series stored in a plain text file named my_data.txt as follows:

0  0
1  1
2  4
4 16
5 25
6 36

A minimalistic pure Python approach to read and plot that data would go as follows:

import matplotlib.pyplot as plt

X, Y = [], []
for line in open('my_data.txt', 'r'):
  values = [float(s) for s in line.split()]
  X.append(values[0])
  Y.append(values[1])

plt.plot(X, Y)
plt.show()

This script, together with the data stored in my_data.txt, will produce the following graph:

How it works...

The following are some explanations ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required