从 Pandas 数据框中绘制堆积条形图和多条形图

Plot Stacked bar chart and Multiple bars chart from Pandas dataframe

我有 CSV 数据被读入 Pandas 数据框,例如:

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

如何根据季度、年份和总计(例如 'new' 或 'renewal' 中的每一个的总和,包括所有状态)绘制堆积条形图?例如,

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

此外,基于相同的数据框,我如何绘制多条形图,例如,对于 2019 年第一季度,第一个条形图是 'new'(总共 10 个)和 'renewal' 作为下一个小节?

看起来像这样:

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

在此先感谢您的帮助!!

您可以尝试 pivot_table 重塑数据:

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

输出:

要并排显示条形图,只需删除堆栈参数:

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

输出: