简体   繁体   English

Matplotlib 中的堆积条形图

[英]Stacked Bar Chart in Matplotlib

I am trying to create stacked Bar Chart in Matplotlib.我正在尝试在 Matplotlib 中创建堆叠条形图。 I have created a simple one using Pandas, but i am now interested in Matplotlib one but cant make it work.我使用 Pandas 创建了一个简单的,但我现在对 Matplotlib 感兴趣,但无法使其工作。

My data我的资料

    ShiftType   ShiftNumber cnt
0   Non-Standard    1.0 154478
1   Non-Standard    2.0 140421
2   Non-Standard    3.0 159990
3   Standard    1.0 211100
4   Standard    2.0 198652
5   Standard    3.0 190857

Code that works using Pandas.使用 Pandas 工作的代码。

df.groupby(by=['ShiftType','ShiftNumber']).size().rename('cnt').unstack().plot(kind='bar', stacked=True)
plt.legend(title='Shift Numbers', bbox_to_anchor=(1.0, 1), loc='upper left')

在 Python 中使用 Pandas 的堆积条形图

How can i get this based on Matplotlib?我怎样才能基于 Matplotlib 得到这个?

The sample code you provided does not accurately tally the sum.您提供的示例代码没有准确计算总和。 It's also somewhat unclear what you mean by "create stacked Bar Chart in Matplotlib" as the Pandas plot() function you called is a matplotlib integration. “在 Matplotlib 中创建堆叠条形图”的含义也有些不清楚,因为您调用的 Pandas plot() 函数是 matplotlib 集成。 Regardless, as standard (and possibly best) practice, I regularly use figure and axes to set up my plots.无论如何,作为标准(也可能是最佳)实践,我经常使用图形和轴来设置我的绘图。 This allows careful control of the plots which I think you are trying to do here.这允许仔细控制我认为你在这里尝试做的情节。

I would suggest this code as a solution to your question and starting point for further plot manipulation.我建议将此代码作为您问题的解决方案和进一步绘图操作的起点。

fig, ax = plt.subplots()

df.groupby(['ShiftType', 'ShiftNumber']) \
    ['cnt'].sum() \
    .reset_index() \
    .pivot_table(index='ShiftType', columns='ShiftNumber', values='cnt') \
    .plot(kind='bar', stacked=True, ax=ax)
ax.legend(title='Shift Numbers', bbox_to_anchor=(1.0, 1), loc='upper left')

I would then add some standard features that every chart should have, for example a y-label and a title.然后我会添加一些每个图表都应该有的标准功能,例如一个 y 标签和一个标题。

ax.set_ylabel('cnt')
ax.set_title('Count of Shift Types')

Combining those, you will then get this final plot.结合这些,你将得到这个最终的情节。

ShiftType 堆积条形图

There might be someting more compact but here is a solution.可能有一些更紧凑的,但这里有一个解决方案。 Here is your df这是你的 df

     ShiftType  ShiftNumber     cnt
0  Non-Standard          1.0  154478
1  Non-Standard          2.0  140421
2  Non-Standard          3.0  159990
3      Standard          1.0  211100
4      Standard          2.0  198652
5      Standard          3.0  190857
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
fig, ax = plt.subplots(figsize=(10,7))  

m = df['ShiftNumber'].drop_duplicates()
margin_bottom = np.zeros(len(df['ShiftType'].drop_duplicates()))
colors = ["#006D2C", "#31A354","#74C476"]

for num, m in enumerate(m):
    values = list(df[df['ShiftNumber'] == m].loc[:, 'cnt'])

    df[df['ShiftNumber'] == m].plot.bar(x='ShiftType',y='cnt', ax=ax, stacked=True, 
                                    bottom = margin_bottom, color=colors[num], label=m)
    margin_bottom += values

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM