- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to plot data from multiple two-column text files with legends in Matplotlib?
To plot data from multiple two-column text files with legends in matplotlib, we can take the following steps −
Import genfromtxt from pylab. It has several options to read data from a text file and plot the data.
Read two text files, test.txt and test1.txt (having two columns of data), using genfromtxt and store the data in two variables, firstfiledata and secondfiledata.
Plot the data using plot() method. label will be displayed as the legend.
To display the figure, use show() method.
Example
from matplotlib import pyplot as plt; from pylab import genfromtxt; plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True firstfiledata = genfromtxt("test.txt"); secondfiledata = genfromtxt("test1.txt"); plt.plot(firstfiledata[:, 0], firstfiledata[:, 1], label="test.txt Data"); plt.plot(secondfiledata[:, 0], secondfiledata[:, 1], label="test1.txt Data"); plt.legend(); plt.show();
Output
Suppse the two text files have the following data −
test.txt ======== 1 3 2 5 3 27 4 9 5 11 6 13 7 15 8 17 9 19
test1.txt ========= 11 13 12 15 13 17 14 19 15 21 16 23 17 25 18 27 19 29
When we execute the code, it will produce the following output −
- Related Articles
- How to get all the legends from a plot in Matplotlib?
- How to plot two Pandas time series on the same plot with legends and secondary Y-axis in Matplotlib?
- How to plot single data with two Y-axes (two units) in Matplotlib?
- Plot data from CSV file with Matplotlib
- How to extract data from a Matplotlib plot?
- How to plot multiple graphs in Matplotlib?
- How to read multiple text files from a folder in Python?(Tkinter)
- How to plot multiple histograms on same plot with Seaborn using Matplotlib?
- Drawing multiple legends on the same axes in Matplotlib
- How to plot a Bar Chart with multiple labels in Matplotlib?
- How to plot multiple horizontal bars in one chart with matplotlib?
- How to plot with multiple color cycle using cycler property in Matplotlib
- How to plot a line graph from histogram data in Matplotlib?
- How to plot data into imshow() with custom colormap in Matplotlib?
- How to add text inside a plot in Matplotlib?

Advertisements