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 ...

Get matplotlib Plotting Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.