2

I have CSV data that is read into a Pandas dataframe such as:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("membership-applications.csv", delimiter=";")
df.sort_values(by=['year', 'quarter'], inplace=True, ascending=True)

quarter,year,type,status,total
Q1,2019,new,approved,10
Q1,2019,renewal,approved,30
Q2,2019,new,approved,10
Q2,2019,new,rejected,20
Q2,2019,renewal,0
Q3,2019,new,0
Q3,2019,renewal,0
Q4,2019,new,0
Q4,2019,renewal,0
Q1,2020,new,approved,10
Q1,2020,renewal,approved,50

How can I plot a stacked bar chart based on quarter, year and total (e.g. sum of each of 'new' or 'renewal' including all statuses)? For example,

                                  +------+ 
+------+                          |  10  |
|  10  | +------+                 +------+
+------+ |  10  |                 |      |
|      | +------+                 |  50  |
|  30  | |  20  |                 |      |
|      | |      |                 |      |
+------+ +------+                 +------+
Q1 2019  Q2 2019  Q3 2019 Q4 2019 Q1 2020

Also, based on the same dataframe, how can I a plot multiple-bar chart, for example for Q1 2019, the first bar is 'new' (which a total of 10) and 'renewal' as the next bar?

Something looks like this:

     +--+
     |  |
+--+ |30| 
|10| |  |
+--+ +--+
 Q1 2019

Thanks in advance for your help!!

1 Answer 1

3

you can try pivot_table to reshape the data:

fig = df.pivot_table(index = ['year','quarter'], columns = 'type', values = 'total', dropna=False , fill_value = 0).plot(kind ='bar', stacked = True)

OUTPUT:

enter image description here

To display bar side-by-side just remove the stack parameter:

fig = df.pivot_table(index = ['year','quarter'], columns = 'type', values = 'total', dropna=False , fill_value = 0).plot(kind ='bar')
plt.xticks(rotation = 30)

OUTPUT:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

That is exactly what I am looking for. Amazing work! I am sorry I don't have enough reputation to vote, yet. That is a YES from me :). Thanks a lot!!
No problem... 😌
Just earned enough "reputation" and came back to up vote +1 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.