The Wayback Machine - https://web.archive.org/web/20240817053424/https://www.geeksforgeeks.org/visualize-data-from-csv-file-in-python/
Open In App

Visualize data from CSV file in Python

Last Updated : 03 Mar, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

CSV stands for ‘Comma-Separated Values‘. It means the data(values) in a CSV file are separated by a delimiter i.e., comma. Data in a CSV file is stored in tabular format with an extension of .csv. Generally, CSV files are used with Google spreadsheets or Microsoft Excel sheets. A CSV file contains a number of records with the data spread across rows and columns. In this article, we are going to visualize data from a CSV file in Python.

To extract the data in CSV file, CSV module must be imported in our program as follows:

import csv

with open('file.csv') as File:  
    Line_reader = csv.reader(File) 

Here, csv.reader( ) function is used to read the program after importing CSV library.

Example 1: Visualizing the column of different persons through bar plot.

The below CSV file contains different person name, gender, and age saved as ‘biostats.csv’:

The approach of the program:

  1. Import required libraries, matplotlib library for visualizing, and CSV library for reading CSV data.
  2. Open the file using open( ) function with ‘r’ mode (read-only) from CSV library and read the file using csv.reader( ) function.
  3. Read each line in the file using for loop.
  4. Append required columns into a list.
  5. After reading the whole CSV file, plot the required data as X and Y axis.
  6. In this example, we are plotting names as X-axis and ages as Y-axis.

Below is the implementation:

Python3




import matplotlib.pyplot as plt
import csv
  
x = []
y = []
  
with open('biostats.csv','r') as csvfile:
    plots = csv.reader(csvfile, delimiter = ',')
      
    for row in plots:
        x.append(row[0])
        y.append(int(row[2]))
  
plt.bar(x, y, color = 'g', width = 0.72, label = "Age")
plt.xlabel('Names')
plt.ylabel('Ages')
plt.title('Ages of different persons')
plt.legend()
plt.show()


Output :

Example 2: Visualizing Weather Report on different Dates” through-line plot.

Temperature(°C) on different dates is stored in a CSV file as ‘Weatherdata.csv’. These two rows ‘Dates’ and ‘Temperature(°C )’ are used as X and Y-axis for visualizing weather reports.

Approach of the program:

  1. Import required libraries, matplotlib library for visualizing, and csv library for reading CSV data.
  2. Open the file using open( )  function with ‘r’ mode (read-only) from CSV library and read the file using csv.reader( ) function.
  3. Read each line in the file using for loop.
  4. Append required columns of the CSV file into a list.
  5. After reading the whole CSV file, plot the required data as X and Y axis.
  6. In this Example, we are plotting Dates as X-axis and Temperature(°C ) as Y-axis.

Below is the implementation:

Python3




import matplotlib.pyplot as plt
import csv
  
x = []
y = []
  
with open('Weatherdata.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=',')
    for row in lines:
        x.append(row[0])
        y.append(int(row[1]))
  
plt.plot(x, y, color = 'g', linestyle = 'dashed',
         marker = 'o',label = "Weather Data")
  
plt.xticks(rotation = 25)
plt.xlabel('Dates')
plt.ylabel('Temperature(°C)')
plt.title('Weather Report', fontsize = 20)
plt.grid()
plt.legend()
plt.show()


Output :

Example 3: Visualizing patients blood pressure report of a hospital through Scatter plot

Approach of the program “Visualizing patients blood pressure report” through Scatter plot :

  1. Import required libraries, matplotlib library for visualization and importing csv library for reading CSV data.
  2. Open the file using open( ) function with ‘r’ mode (read-only) from CSV library and read the file using csv.reader( ) function.
  3. Read each line in the file using for loop.
  4. Append required columns of the CSV file into a list.
  5. After reading the whole CSV file, plot the required data as X and Y axis.
  6. In this example, we are plotting the Names of patients as X-axis and Blood pressure values as Y-axis.

Below is the implementation:

Python3




import matplotlib.pyplot as plt
import csv
  
Names = []
Values = []
  
with open('bldprs_measure.csv','r') as csvfile:
    lines = csv.reader(csvfile, delimiter=',')
    for row in lines:
        Names.append(row[0])
        Values.append(int(row[1]))
  
plt.scatter(Names, Values, color = 'g',s = 100)
plt.xticks(rotation = 25)
plt.xlabel('Names')
plt.ylabel('Values')
plt.title('Patients Blood Pressure Report', fontsize = 20)
  
plt.show()


Output :

Example 4: Visualizing Student marks in different subjects using a pie plot

Approach of the program:

  1. Import required libraries, matplotlib library for visualization and importing csv library for reading CSV data.
  2. Open the file using open( )  function with ‘r’ mode (read-only) from CSV library and read the file using csv.reader( ) function.
  3. Read each line in the file using for loop.
  4. Append required columns of the CSV file into lists.
  5. After reading the whole CSV data, plot the required data as pie plot using plt.pie( ) function.

Below is the implementation:

Python3




import matplotlib.pyplot as plt
import csv
  
Subjects = []
Scores = []
  
with open('SubjectMarks.csv', 'r') as csvfile:
    lines = csv.reader(csvfile, delimiter = ',')
    for row in lines:
        Subjects.append(row[0])
        Scores.append(int(row[1]))
  
plt.pie(Scores,labels = Subjects,autopct = '%.2f%%')
plt.title('Marks of a Student', fontsize = 20)
plt.show()


Output :



Previous Article
Next Article

Similar Reads

How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 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 Python is used to connect MySQL databases with the P
5 min read
Analyze and Visualize Earthquake Data in Python with Matplotlib
Earthquake is a natural phenomenon whose occurrence predictability is still a hot topic in academia. This is because of the destructive power it holds. In this article, we'll learn how to analyze and visualize earthquake data with Python and Matplotlib. Importing Libraries and Dataset Python libraries make it very easy for us to handle the data and
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
How to convert CSV File to PDF File using Python?
In this article, we will learn how to do Conversion of CSV to PDF file format. This simple task can be easily done using two Steps : Firstly, We convert our CSV file to HTML using the PandasIn the Second Step, we use PDFkit Python API to convert our HTML file to the PDF file format. Approach: 1. Converting CSV file to HTML using Pandas Framework. P
3 min read
How to visualize selection and insertion sort using Tkinter in Python?
In this article, we are going to create a GUI application that will make us visualize and understand two of the most popular sorting algorithms better, using Tkinter module. Those two sorting algorithms are selection sort and insertion sort. Selection sort and Insertion sort are the two most popular algorithms. Selection sort is a comparison-based
6 min read
How To Visualize Sparse Matrix in Python using Matplotlib?
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. Visualize Sparse Matrix using Matplotlib Spy is a function used to visualize the array as an image similar to matplotlib imshow function,
3 min read
Visualize Graphs in Python
Prerequisites: Graph Data Structure And Algorithms A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. In this tutorial we are going to visualize undirected Graphs in Python with the help of networkx librar
2 min read
How to Visualize a Neural Network in Python using Graphviz ?
In this article, We are going to see how to plot (visualize) a neural network in python using Graphviz. Graphviz is a python module that open-source graph visualization software. It is widely popular among researchers to do visualizations. It's representing structural information as diagrams of abstract graphs and networks means you only need to pr
4 min read
Visualize sinusoidal waves using Python
Sinusoidal waves are the most basic trigonometric periodic curves, which is also known as the sine curve. Here we will see how sine function is related to a circle. Even though the sine function is a trigonometric function, it has more to do with a circle rather than a triangle. Consider a simple equation of a circle: [Tex]x^2 + y^2 = r^2 [/Tex] wh
5 min read
Visualize Merge sort Using Tkinter in Python
Prerequisites: Python GUI – tkinter In this article, we will create a GUI application that will help us to visualize the algorithm of merge sort using Tkinter in Python. Merge Sort is a popular sorting algorithm. It has a time complexity of N(logN) which is faster than other sorting algorithms like a bubble or selection sort. By creating this appli
5 min read
Saving a Networkx graph in GEXF format and visualize using Gephi
Prerequisites: Networkx NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics, and function of complex networks. It is used to study large complex networks represented in form of graphs with nodes and edges. Using networkx we can load and store complex networks. We can generate many type
2 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
How to Sort data by Column in a CSV File in Python ?
In this article, we will discuss how to sort CSV by column(s) using Python. Method 1: Using sort_values() We can take the header name as per our requirement, the axis can be either 0 or 1, where 0 means 'rows' and '1' means 'column'. Ascending can be either True/False and if True, it gets arranged in ascending order, if False, it gets arranged in d
3 min read
How to resolve a UnicodeDecodeError for a CSV file in Python?
Several errors can arise when an attempt to decode a byte string from a certain coding scheme is made. The reason is the inability of some encoding schemes to represent all code points. One of the most common errors during these conversions is UnicodeDecode Error which occurs when decoding a byte string by an incorrect coding scheme. This article w
5 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
How to delete a CSV file in Python?
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Approach : Import module.Check the path of the file.
2 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Image.open() and numpy.asarray(). Example: C/C++ Code
4 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Replacing column value of a CSV file in Python
Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-delimited file. Method 1: Using Native Python way Using replace() method, we can replace easily a text into another text. In the below code, let us have an input CSV file as "csvfile.csv" and be opened in "read" mode. The join() method takes all
2 min read
How to add a header to a CSV file in Python?
A CSV file contains a tabular sort of data where each row contains comma-separated values. The columns may contain values belonging to different data structures. Python provides a wide range of methods and modules to carry out the interconversion of the CSV file to a pandas data frame and vice versa. A header of the CSV file is an array of values a
2 min read
How to count the number of lines in a CSV file in Python?
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the n
2 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 label is the name of a particular bar and value r
2 min read
Exporting variable to CSV file in Python
The CSV file or comma-separated values file is used to store and share data across platforms. The columns are separated by commas or other relevant delimiters, giving the data a tabular structure. Sometimes we come across ready-made CSV files while sometimes we need to create one according to the requirements in our projects. Python can write CSV f
3 min read
Scrape IMDB movie rating and details using Python and saving the details of top movies to .csv file
We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python. Modules Needed: Below is the list of modules required to scrape from IMDB. requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests must be learne
4 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
How to import CSV file in SQLite database using Python ?
In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. Approach: Importing necessary modulesRead data from CSV file DictReader()Establish a connection with the database.sqlit
2 min read
How to add timestamp to CSV file in Python
Prerequisite: Datetime module In this example, we will learn How to add timestamp to CSV files in Python. We can easily add timestamp to CSV files with the help of datetime module of python. Let's the stepwise implementation for adding timestamp to CSV files in Python. Creating CSV and adding timestampImport csv and datetime module. We will use the
5 min read
three90RightbarBannerImg