【问题标题】:Matplotlib: Stacked Bar GraphMatplotlib:堆积条形图
【发布时间】:2019-11-28 23:22:29
【问题描述】:

给定一个 pandas df,我想创建堆叠条形图,其中每行的所有值都堆叠在每个条形中。我希望 xticks 是索引号,y 值是每行堆积条的总和。但是我一直没能做到。

我得到 TypeError:当我尝试绘图时,只有 size-1 数组可以转换为 Python 标量

我尝试将每一行追加到一个数组中,但我最终多次追加了相同的排列。

我在这里按照示例进行操作:https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/bar_stacked.html#stacked-bar-graph

import pandas as pd
import matplotlib as plt

index   C1              C2              C3
1   48692.4331  34525.0003  14020.1233
2   43206.1635  27978.9984  16572.0428
3   67398.4482  49903.4956  29856.5693


no_1 = [df["C1"] for index in df.index]
no_2 = [df["C2"] for index in df.index]
no_3 = [df["C3"] for index in df.index]

N = 3
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, no_1, width)
p2 = plt.bar(ind, no_2, width, bottom=no_1)
p3 = plt.bar(ind, no_3, width, bottom=no_2)

plt.xticks(ind, ('no_1', 'no_2', 'no_3'))

【问题讨论】:

    标签: python arrays pandas matplotlib bar-chart


    【解决方案1】:

    你可以使用pandas.DataFrame.plot:

    df.rename(lambda x: 'no_'+str(x), axis='index').plot.bar(stacked=True)
    

    输出:


    出于学习目的:

    xlabels = 'no_'+ df.index.astype(str)
    _ = plt.bar(xlabels, df['C1'])
    _ = plt.bar(xlabels, df['C2'], bottom=df['C1'])
    _ = plt.bar(xlabels, df['C3'], bottom=df[['C1','C2']].sum(1))
    

    输出:

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2017-11-02
      • 2021-02-27
      • 1970-01-01
      • 2017-09-19
      • 2023-03-11
      • 2018-03-10
      相关资源
      最近更新 更多