Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot data from multiple two column text files with legends in Matplotlib?

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

like image 726
Hiren Avatar asked Jun 28 '12 16:06

Hiren


People also ask

How do I plot multiple legends in MatPlotLib?

MatPlotLib with PythonPlace the first legend at the upper-right location. Add artist, i.e., first legend on the current axis. Place the second legend on the current axis at the lower-right location. To display the figure, use show() method.

How do you plot multiple columns in Python?

You can plot data directly from your DataFrame using the plot() method. To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function.


1 Answers

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.

like image 138
cge Avatar answered Sep 19 '22 22:09

cge