Open In App

Visualize data from CSV file in Python

Last Updated : 03 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 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
Python | Visualize graphs generated in NetworkX using Matplotlib
Prerequisites: Generating Graph using Network X, Matplotlib IntroIn this article, we will be discussing how to plot a graph generated by NetworkX in Python using Matplotlib. NetworkX is not a graph visualizing package but basic drawing with Matplotlib is included in the software package. Step 1 : Import networkx and matplotlib.pyplot in the project
3 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
three90RightbarBannerImg