How To Plot Bar Graph In Python Using CSV File
Last Updated : Jan 1, 2023
IN - Python
In this article we will show you the solution of how to plot bar graph in python using csv file, in simple terms bar graph means bar chart, it is used for representation of data.
And CSV file means a (comma- separated values) file is a text file that has a special arrangement which allows data to be saved in a table structured arrangement.
Step By Step Guide On How To Plot Bar Graph In Python Using CSV File :-
A bar graph is a map that plots data using blockish bars or columns (called boxes) that represent the total volume of observances in the data for that order.
Bar maps can be displayed with perpendicular columns, vertical bars, relative bars (multiple bars to display a comparison between values), or piled bars (bars holding many varieties of data).
A CSV File (comma- separated values) is a text file that stores data in the configuration of columns, separated by commas, and rows are separated by line breaks.
Comma separated value file means that the data is truly intake as data that's separated by commas.
The spreadsheet usage converts those comma- separated bits of data into cells in tables and columns to produce it simple to read and edit.
There are plenty of modules accessible to read a. csv file like csv, pandas, etc.
Following are the steps for plotting the bar graph in python using csv file.
- Import module
- Read file using read_csv() function
- Plot bar graph
- Display graph
import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('data.csv') df = pd.DataFrame(data) X = list(df.iloc[:, 0]) Y = list(df.iloc[:, 1]) plt.bar(X, Y, color='g') plt.title("innovative companies") plt.xlabel("Countries") plt.ylabel("Number of Companies") plt.show()
- In the first two lines of code, we import modules. Matplotlib for creating bar graph and pandas for reading csv file.
- After that we use csv file for reading data.
- Then we create the dataframe.
- Then we initialize the lists for X and Y.
- We use .iloc which is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array.
- Then we plot the bar graph using bar method
- Then we display the graph by using show method.
Hence, we have successfully learnt how plot the bar graph with the help of csv file in python.
I hope this article on how to plot bar graph in python using csv file helps you and the steps and method mentioned above are easy to follow and implement.