How to generate grouped BAR plot in Python?
DATA VISUALIZATION

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

0
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 [3]:
## How to generate grouped BAR plot in Python
def Snippet_117():
    print()
    print(format('How to generate grouped BAR plot in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd
    import matplotlib.pyplot as plt

    # Create dataframe
    raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
                'pre_score': [4, 24, 31, 2, 3],
                'mid_score': [25, 94, 57, 62, 70],
                'post_score': [5, 43, 23, 23, 51]}
    df = pd.DataFrame(raw_data, columns = ['first_name', 'pre_score', 'mid_score', 'post_score'])
    print(); print(df)

    # Setting the positions and width for the bars
    pos = list(range(len(df['pre_score'])))
    width = 0.25

    # Plotting the bars
    fig, ax = plt.subplots(figsize=(10,5))

    # Create a bar with pre_score data
    plt.bar(pos, df['pre_score'], width, alpha=0.5, color='#EE3224')
    #plt.show()

    # Create a bar with mid_score data,
    plt.bar([p + width for p in pos], df['mid_score'], width, alpha=0.5, color='#F78F1E')
    #plt.show()

    # Create a bar with post_score data,
    plt.bar([p + width*2 for p in pos], df['post_score'], width, alpha=0.5, color='#FFC222')
    #plt.show()

    # Set the y axis label
    ax.set_ylabel('Score')

    # Set the chart's title
    ax.set_title('Test Subject Scores')

    # Set the position of the x ticks
    ax.set_xticks([p + 1.5 * width for p in pos])

    # Set the labels for the x ticks
    ax.set_xticklabels(df['first_name'])

    # Setting the x-axis and y-axis limits
    plt.xlim(min(pos)-width, max(pos)+width*4)
    plt.ylim([0, max(df['pre_score'] + df['mid_score'] + df['post_score'])] )

    # Adding the legend and showing the plot
    plt.legend(['Pre Score', 'Mid Score', 'Post Score'], loc='upper left')
    plt.grid()
    plt.show()

Snippet_117()
********************How to generate grouped BAR plot in Python********************

  first_name  pre_score  mid_score  post_score
0      Jason          4         25           5
1      Molly         24         94          43
2       Tina         31         57          23
3       Jake          2         62          23
4        Amy          3         70          51

Relevant Projects

PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

Choosing the right Time Series Forecasting Methods
There are different time series forecasting methods to forecast stock price, demand etc. In this machine learning project, you will learn to determine which forecasting method to be used when and how to apply with time series forecasting example.

Music Recommendation System Project using Python and R
Machine Learning Project - Work with KKBOX's Music Recommendation System dataset to build the best music recommendation engine.

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.

Data Science Project-TalkingData AdTracking Fraud Detection
Machine Learning Project in R-Detect fraudulent click traffic for mobile app ads using R data science programming language.

Anomaly Detection Using Deep Learning and Autoencoders
Deep Learning Project- Learn about implementation of a machine learning algorithm using autoencoders for anomaly detection.

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

Data Science Project-All State Insurance Claims Severity Prediction
Data science project in R to develop automated methods for predicting the cost and severity of insurance claims.

Predict Census Income using Deep Learning Models
In this project, we are going to work on Deep Learning using H2O to predict Census income.

Mercari Price Suggestion Challenge Data Science Project
Data Science Project in Python- Build a machine learning algorithm that automatically suggests the right product prices.