How to generate grouped BAR plot in Python?
DATA VISUALIZATION DATA CLEANING PYTHON DATA MUNGING MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to generate grouped BAR plot in Python?

How to generate grouped BAR plot in Python?

This recipe helps you generate grouped BAR plot in Python

Recipe Objective

It is very easy to understand the data if we have visual representation of data. Visual representation of data can be done in many formats like histograms, pie chart, bar graphs etc

This python source code does the following:
1. Creates and converts data dictionary into dataframe
2. Groups different bar graphs
3. Plots the bar graphs by adjusting the position of bars

In this code recipe we will learn how to plot bar graphs for different class of data.

Step 1 - Import the library

import pandas as pd import matplotlib.pyplot as plt

We have imported pandas and plt from matplotlib.pyplot library.

Step 2 - Setup the Data

Here we have created a dictionary named exam_data and passed that in pd.DataFrame to create a DataFrame with columns 'name', 'Maths_score', 'Science_score' and 'French_score'. We have also used a print statement to print the dataframe. exam_data = {'name': ['Aman', 'Alen', 'Mona', 'Jhon', 'Sheldon'], 'Maths_score': [44, 24, 31, 10, 16], 'Science_score': [25, 44, 7, 62, 75], 'French_score': [5, 13, 63, 53, 40]} df = pd.DataFrame(exam_data, columns = ['name', 'Maths_score', 'Science_score', 'French_score']) print(df)

Step 3 - Setting Position and Width of the bars in Graph

There have various strings in the column 'names' and for all of that we have to plot the bars. So for that we have to set the position of the bars. We are defining objects for position and width of bars and we are calling subplots with size of the figure as a parameter. pos = list(range(len(df['Maths_score']))) width = 0.25 fig, ax = plt.subplots(figsize=(10,5))

Step 5 - Creating bars for the data

Now we have to plot the bars for the data by plt.bar. Let us have a look on the parameters first:

  • x : In this parameter we have to pass the values for which we want to plot bars.
  • width : It this parameter we have to set the width of the bars. By default it is 0.8
  • aplha : In this parameter we have to pass values between 0 and 1 and it is a parameter to set the transparency of the bars.
  • color : It this parameter we have to pass the colour code in which we want to have the bars.
  • pos : In this parameter we have to set the position of the bars.
  • align : It this parameter we have to set the alignment of the bar by center or edge. By default it is center.
plt.bar(pos, df['Maths_score'], width, alpha=0.5, color='#EE3224') plt.bar([p + width for p in pos], df['Science_score'], width, alpha=0.5, color='#F78F1E') plt.bar([p + width*2 for p in pos], df['French_score'], width, alpha=0.5, color='#FFC222') Now have to set the other elements of the graph like x and y axis label, title of graph, setting x and y axis limits and the legend. These all can be done by the functiond below with the comments given. After that we can set the grid by plt.grid() and we can view the graph by plt.show(). # Setting the y axis label ax.set_ylabel('Score') # Setting the chart's title ax.set_title('Test Subject Scores') # Setting the position of the x ticks ax.set_xticks([p + 1.5 * width for p in pos]) # Setting the labels for the x ticks ax.set_xticklabels(df['name']) # Setting the x-axis and y-axis limits plt.xlim(min(pos)-width, max(pos)+width*4) plt.ylim([0, max(df['Maths_score'] + df['Science_score'] + df['French_score'])] ) # Adding the legend and showing the plot plt.legend(['Maths Score', 'Science Score', 'French Score'], loc='upper left') plt.grid() plt.show() So the output comes as

      name  Maths_score  Science_score  French_score
0     Aman           44             25             5
1     Alen           24             44            13
2     Mona           31              7            63
3     Jhon           10             62            53
4  Sheldon           16             75            40

Download Materials

Relevant Projects

Churn Prediction in Telecom using Machine Learning in R
Estimating churners before they discontinue using a product or service is extremely important. In this ML project, you will develop a churn prediction model in telecom to predict customers who are most likely subject to churn.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Forecasting Business KPI's with Tensorflow and Python
In this machine learning project, you will use the video clip of an IPL match played between CSK and RCB to forecast key performance indicators like the number of appearances of a brand logo, the frames, and the shortest and longest area percentage in the video.

Avocado Machine Learning Project Python for Price Prediction
In this ML Project, you will use the Avocado dataset to build a machine learning model to predict the average price of avocado which is continuous in nature based on region and varieties of avocado.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

NLP and Deep Learning For Fake News Classification in Python
In this project you will use Python to implement various machine learning methods( RNN, LSTM, GRU) for fake news classification.

Build a Similar Images Finder with Python, Keras, and Tensorflow
Build your own image similarity application using Python to search and find images of products that are similar to any given product. You will implement the K-Nearest Neighbor algorithm to find products with maximum similarity.

House Price Prediction Project using Machine Learning
Use the Zillow dataset to follow a test-driven approach and build a regression machine learning model to predict the price of the house based on other variables.

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.