Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python plot
bar graphs

How to make bar graphs using pandas

Educative Answers Team

pandas is a popular Python-based data analysis toolkit that can be imported using:

import pandas as pd

It presents a diverse range of utilities from parsing multiple file-formats to converting an entire data table into a NumPy matrix array. This property makes pandas a trusted ally in data science and machine learning.

pandas can help you in the creation of multiple types of data analysis graphs. One such graph is the bar graph.

The default implementation of the bar graph is:

DataFrame.bar(x = None y= None, color= None, **kwargs)

Parameters

  • x: label or position - Allows plotting of one column versus the other. If not provided, the index of the df is used.

  • y: label or position - Allows plotting of one column versus the other. If not provided, all numerical columns are used.

  • color: str, array-like, dict - Color for each column. Possible values are:
    Single string referenced in RGB, or RGBA code - used for all columns
    Array referenced in RGB, or RGBA code - used for columns recursively
    Dict - used for all columns specified. For example, {‘Col1’: ‘red’} will apply red color to the column named Col1.

  • **kwargs: tuple (rows, columns) - All other plotting keyword arguments to be passed to matplotlib.pyplot.boxplot().

Code

Let’s look at an example. Import the library and load the dataset in the data frame. Here, the dataset includes the mean for multiple subjects:

#import library
import pandas as pd

#add csv file to dataframe
df = pd.DataFrame({'Subject': ['English', 'Maths', 'Science'], 'Mean': [90, 87, 67]})

#create bar graph
bargraph = df.plot.bar(x = 'Subject', y = 'Mean', fontsize='9')

You can plot a complete data frame in a similar manner:

main.py
dataset.csv
#import library
import pandas as pd

#add csv file to dataframe
df = pd.read_csv('dataset.csv')

#create bar graph
bargraph = df.plot.bar(x = 'Id')

RELATED TAGS

pandas
python plot
bar graphs
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring