28

How do I open multiple text files from different directories and plot them on a single graph with legends?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Hiren
  • 301
  • 1
  • 3
  • 7

3 Answers3

30

This is relatively simple if you use pylab (included with matplotlib) instead of matplotlib directly. Start off with a list of filenames and legend names, like [ ('name of file 1', 'label 1'), ('name of file 2', 'label 2'), ...]. Then you can use something like the following:

import pylab

datalist = [ ( pylab.loadtxt(filename), label ) for filename, label in list_of_files ]

for data, label in datalist:
    pylab.plot( data[:,0], data[:,1], label=label )

pylab.legend()
pylab.title("Title of Plot")
pylab.xlabel("X Axis Label")
pylab.ylabel("Y Axis Label")

You also might want to add something like fmt='o' to the plot command, in order to change from a line to points. By default, matplotlib with pylab plots onto the same figure without clearing it, so you can just run the plot command multiple times.

cge
  • 9,552
  • 3
  • 32
  • 51
  • Thank You for helping me, but i am running in to some problems. What is the purpose for "list_of_files". In addition, when i type pylab.plot( data[:,0], data[:,1], label=label ) i get this []. IF you could help me that be great thank You. – Hiren Jun 29 '12 at 23:03
  • The list_of_files is for if you want to plot multiple files: just do something like list_of_files = [ ('path to file 1', 'label 1'), ('path to file 2', 'label 2'), ...], and the code will plot all of them on the same plot with those labels. As for the output you get, that's the usual output; the plot should show up in a separate window? If not, you have a problem with your matplotlib installation. Are you using ipython? If so, are you using ipython notebook or just standard ipython? – cge Jun 30 '12 at 20:20
  • Thank You and i am able to make it wrk now. I have one issue though which is that the saved plot has old graphs in the new graph and only way for me to have a new graphs is by restarting the python IDLE. Do you why that is? i want to have multiple graphs but not with previous graph from last figure/ graph. – Hiren Jul 02 '12 at 18:52
  • I was able to fix this by having a figure() command before the plot. Thank You. – Hiren Jul 02 '12 at 18:56
  • 5
    @Hiren If it resolved your question, would you please accept it as answer? – skjoshi Aug 26 '14 at 12:00
  • pylad.loadtxt did not work for me, but import numpy then numpy.loadtxt did – Chris May 19 '17 at 04:00
20

Assume your file looks like this and is named test.txt (space delimited):

1 2
3 4
5 6
7 8

Then:

#!/usr/bin/python

import numpy as np
import matplotlib.pyplot as plt

with open("test.txt") as f:
    data = f.read()

data = data.split('\n')

x = [row.split(' ')[0] for row in data]
y = [row.split(' ')[1] for row in data]

fig = plt.figure()

ax1 = fig.add_subplot(111)

ax1.set_title("Plot title...")    
ax1.set_xlabel('your x label..')
ax1.set_ylabel('your y label...')

ax1.plot(x,y, c='r', label='the data')

leg = ax1.legend()

plt.show()

Example plot:

I find that browsing the gallery of plots on the matplotlib site helpful for figuring out legends and axes labels.

tbc
  • 1,679
  • 3
  • 21
  • 28
  • 1
    Why would you interpret the data directly instead of using np.loadtxt? – cge Jun 28 '12 at 17:01
  • I have never had much luck with np.loadtxt (usually have messier input files), but for this simple example, it would probably work great. – tbc Jun 28 '12 at 17:02
  • Why not use the csv module with delimiter set to space? – Dhara Jun 28 '12 at 18:23
  • 1
    Or, for that matter, numpy.genfromtxt. There are many implemented ways to load text data into numpy. – cge Jun 28 '12 at 20:30
5

I feel the simplest way would be

 from matplotlib import pyplot;
 from pylab import genfromtxt;  
 mat0 = genfromtxt("data0.txt");
 mat1 = genfromtxt("data1.txt");
 pyplot.plot(mat0[:,0], mat0[:,1], label = "data0");
 pyplot.plot(mat1[:,0], mat1[:,1], label = "data1");
 pyplot.legend();
 pyplot.show();
  1. label is the string that is displayed on the legend
  2. you can plot as many series of data points as possible before show() to plot all of them on the same graph This is the simple way to plot simple graphs. For other options in genfromtxt go to this url.
router
  • 582
  • 5
  • 16