How to plot data from a text file using Matplotlib?
Last Updated :
10 Feb, 2023
Perquisites: Matplotlib, NumPy
In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like:
- Bar Graph
- Line Graph
- Scatter Graph
- Histogram Graph and many.
In this article, we will learn how we can load data from a file to make a graph using the "Matplotlib" python module. Here we will also discuss two different ways to extract data from a file. In the First Module, we will discuss extracting data using the inbuilt CVS module and In the Second Module, we will use a third-party "NumPy" Module to extract data from a file.
Requirement:
A text file from where data should be extracted. Let the file name = GFG.txt

Method 1: In this method, we will extract data using CSV module to load CVS files.
Step 1:
Import all required modules.
Python3
import matplotlib.pyplot as plt
import csv
Step 2: Create X and Y variables to store X-axis data and Y-axis data from a text file.
Python3
import matplotlib.pyplot as plt
import csv
X = []
Y = []
Step 3: Open text file in read mode. Pass 'file_name' and delimiter in reader function and store returned data in a new variable.
Python3
import matplotlib.pyplot as plt
import csv
X = []
Y = []
with open('GFG.txt', 'r') as datafile:
plotting = csv.reader(datafile, delimiter=',')
Step 4: Create a loop, that will append the data in X and Y variable.
Python3
import matplotlib.pyplot as plt
import csv
X = []
Y = []
with open('GFG.txt', 'r') as datafile:
plotting = csv.reader(datafile, delimiter=',')
for ROWS in plotting:
X.append(int(ROWS[0]))
Y.append(int(ROWS[1]))
Step 5: Now pass all the parameter in their respective functions.
Python3
import matplotlib.pyplot as plt
import csv
X = []
Y = []
with open('GFG.txt', 'r') as datafile:
plotting = csv.reader(datafile, delimiter=',')
for ROWS in plotting:
X.append(int(ROWS[0]))
Y.append(int(ROWS[1]))
plt.plot(X, Y)
plt.title('Line Graph using CSV')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

Method 2: In this method, we will extract data using numpy module to load files. Here you will notice that Step 2,3 and 4 are replaced by np.loadtxt( )
Python3
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True)
plt.bar(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

You can also try other different graphs by just changing 1 line
plt.plot(X,Y) to plt.scatter(X,Y) or plt.plot(X,Y)
Python3
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True)
plt.plot(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

Python3
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True)
plt.scatter(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

Similar Reads
How to Save a Plot to a File Using Matplotlib? Matplotlib is a popular Python library to create plots, charts, and graphs of different types. show() is used to plot a plot, but it doesn't save the plot to a file. In this article, we will see various methods through which a Matplotlib plot can be saved as an image file.Methods to Save a Plot in M
2 min read
Plot Data from Excel File in Matplotlib - Python Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It is a plotting library for the Python programming language and its numerical mathematics extension NumPy. In this article, we will learn how to plot data from an excel file in Matplotlib.
2 min read
How to Create Matplotlib Plots Without a GUI To create and save plots using Matplotlib without opening a GUI window, you need to configure Matplotlib to use a non-interactive backend. This can be achieved by setting the backend to 'Agg', which is suitable for generating plots without displaying them. Let's see how to set the backend to Agg: Me
2 min read
How to Plot a Dataframe using Pandas Pandas plotting is an interface to Matplotlib, that allows to generate high-quality plots directly from a DataFrame or Series. The .plot() method is the core function for plotting data in Pandas. Depending on the kind of plot we want to create, we can specify various parameters such as plot type (ki
8 min read
How to draw 2D Heatmap using Matplotlib in python? A heatmap is a great tool for visualizing data across the surface. It highlights data that have a higher or lower concentration in the data distribution. A 2-D Heatmap is a data visualization tool that helps to represent the magnitude of the matrix in form of a colored table. In Python, we can plot
5 min read
How to add text to Matplotlib? Matplotlib is a plotting library in Python to visualize data, inspired by MATLAB, meaning that the terms used (Axis, Figure, Plots) will be similar to those used in MATLAB. Pyplot is a module within the Matplotlib library which is a shell-like interface to Matplotlib module. Â It provides almost any
5 min read
How to visualize data from MySQL database by using Matplotlib in Python ? Prerequisites: Matplotlib in Python, MySQL While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python. MySQL Connector module of Py
5 min read
How To Create A Multiline Plot Using Seaborn? Data visualization is a crucial component of data analysis, and plotting is one of the best ways to visualize data. The Python data visualization package Seaborn offers a high-level interface for making visually appealing and educational statistics visuals. The multiline plot, which lets you see num
4 min read
How to plot Bar Graph in Python using CSV file? CSV stands for "comma separated values", that means the values are distinguished by putting commas and newline characters. A CSV file provides a table like format that can be read by almost every spreadsheet reader like Microsoft Excel and Google Spreadsheet. A Bar Graph uses labels and values where
2 min read
How to Plot Mfcc in Python Using Matplotlib? Mel-frequency cepstral coefficients (MFCC) are widely used in audio signal processing and speech recognition tasks. They represent the spectral characteristics of an audio signal and are commonly used as features for various machine-learning applications. In this article, we will explore how to comp
2 min read