How to generate stacked BAR plot in Python?

How to generate stacked BAR plot in Python?

How to generate stacked BAR plot in Python?

This recipe helps you generate stacked BAR plot in Python

Recipe Objective

Graphical representation of data gives us a better idea of the data. Bar graph is one of the way to do that.

So this is the recipe on how we can generate stacked BAR plot in Python.

Step 1 - Importing Library

import pandas as pd import matplotlib.pyplot as plt

We have only imported pandas and matplotlib which is needed.

Step 2 - Creating a dataframe

We have created a dictionary with different values and passed it to pd.DataFrame to create a 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(df)

Step 2 - Creating Bar Graph

We have created a bar graph for that we have to set various things. We have fixed bar width, bar boundries and their position. f, ax = plt.subplots(1, figsize=(10,5)) bar_width = 1 bar_l = [i for i in range(len(df["pre_score"]))] tick_pos = [i+(bar_width/2)-0.5 for i in bar_l] Here we have set the stack segment of the bar graph, by calculating total and individual sum and their percentage. We have also set the position of the bar. totals = [i+j+k for i,j,k in zip(df["pre_score"], df["mid_score"], df["post_score"])] pre_rel = [i / j * 100 for i,j in zip(df["pre_score"], totals)] mid_rel = [i / j * 100 for i,j in zip(df["mid_score"], totals)] post_rel = [i / j * 100 for i,j in zip(df["post_score"], totals)], pre_rel, label="Pre Score", alpha=0.9, width=bar_width, edgecolor="white"), mid_rel, bottom=pre_rel, label="Mid Score", alpha=0.9, width=bar_width, edgecolor="white"), post_rel, bottom=[i+j for i,j in zip(pre_rel, mid_rel)], label="Post Score", alpha=0.9, width=bar_width, edgecolor="white") We are setting the label of x axis, y axis and other parameters of the plot. print(tick_pos) plt.xticks(tick_pos, df["first_name"]) ax.set_ylabel("Percentage") ax.set_xlabel("") plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width]) plt.ylim(-10, 110) plt.setp(plt.gca().get_xticklabels(), rotation=45)

  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
[0.0, 1.0, 2.0, 3.0, 4.0]

Download Materials

Relevant Projects

RASA NLU chatbot creation
The project will use rasa NLU for the Intent classifier, spacy for entity tagging, and mongo dB as the DB. The project will incorporate slot filling and context management and will be supporting the following intent and entities. Intents : product_info | ask_price|cancel_order Entities : product_name|location|order id The project will demonstrate how to generate data on the fly, annotate using framework and how to process those for different pieces of training as discussed above .

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

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.

Build a Collaborative Filtering Recommender System in Python
Use the Amazon Reviews/Ratings dataset of 2 Million records to build a recommender system using memory-based collaborative filtering in Python.

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.

Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.

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.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Grouping similar schools/colleges using scorecard and other factors
Use cluster analysis to identify the groups of characteristically similar schools in the College Scorecard dataset. Considerations: Clustering Algorithm Data Preparation How will you deal with missing values? Categorical variables? Feature intercorrelations? Feature normalization or scaling? Dimensionality reduction? Hyperparameters How will you set the parameters -- the algorithm's knobs and dials, so to speak -- in order to achieve valid and useful output? Interpretation Is it possible to explain what each cluster represents? Did you retain or prepare a set of features that enables a meaningful interpretation of the clusters? Do the compositions of the clusters seem to make sense? Validation How will you measure the validity of your clustering process? Which metrics will you use and how will you apply them?

Machine Learning Project to Forecast Rossmann Store Sales
In this machine learning project you will work on creating a robust prediction model of Rossmann's daily sales using store, promotion, and competitor data.