【问题标题】:Stacked Bar Chart in MatplotlibMatplotlib 中的堆积条形图
【发布时间】:2021-02-27 15:46:24
【问题描述】:

我正在尝试在 Matplotlib 中创建堆叠条形图。我使用 Pandas 创建了一个简单的,但我现在对 Matplotlib 感兴趣,但无法使其工作。

我的数据

    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

使用 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')

我怎样才能基于 Matplotlib 得到这个?

【问题讨论】:

  • pandas 使用 matplotlib 进行绘图,因此显然您可以在 matplotlib 中重新创建它。但这听起来像是一个 x-y 问题。捕获轴对象以进行进一步的图像处理ax = df.groupby(by=['ShiftType','...().plot(kind='bar', stacked=True),然后更改轴对象,例如ax.tick_params(axis='x', labelrotation=45)。顺便说一句,您的示例代码似乎不正确 - 它没有总结 cnt 部分。

标签: python python-3.x pandas matplotlib


【解决方案1】:

可能有一些更紧凑的东西,但这里有一个解决方案。这是你的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()

【讨论】:

  • 不起作用!首先,月份变量是错误的。我也尝试过这个例子,但失败了。请使用我的 df 构建解决方案。
【解决方案2】:

您提供的示例代码未准确计算总和。您所说的“在 Matplotlib 中创建堆叠条形图”的含义也有些不清楚,因为您调用的 Pandas plot() 函数是一个 matplotlib 集成。无论如何,作为标准(并且可能是最佳)实践,我经常使用图形和轴来设置我的绘图。这允许仔细控制我认为你在这里尝试做的情节。

我建议将此代码作为您的问题的解决方案和进一步处理绘图的起点。

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')

然后我会添加一些每个图表都应该具有的标准功能,例如 y 标签和标题。

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

结合这些,您将得到最终的情节。

【讨论】:

    猜你喜欢
    • 2018-01-17
    • 2019-11-28
    • 2017-09-19
    • 2017-11-02
    • 1970-01-01
    • 2013-05-15
    • 2012-12-24
    相关资源
    最近更新 更多