简体   繁体   English

Matplotlib:堆积条形图

[英]Matplotlib: Stacked Bar Graph

Given a pandas df I want to create Stacked Bar Graphs where all the values per row are stacked in each bar. 给定一个熊猫df,我想创建堆积条形图,其中每行的所有值都堆积在每个条形图中。 I want the xticks to be the index number and the y value to be the sum of the stacked bars of each row. 我希望xticks是索引号,而y值是每行堆叠的条的总和。 However I haven´t been able to achieve it. 但是我还没有实现它。

I get TypeError: only size-1 arrays can be converted to Python scalars when I try to do the plot 我收到TypeError:当我尝试执行绘图时,只能将size-1数组转换为Python标量

I've tried to append each row in an array but I end up appending the same arrange multiple times. 我尝试将每个行追加到数组中,但最终却多次追加相同的安排。

I'm following the example here: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/bar_stacked.html#stacked-bar-graph 我在这里遵循以下示例: 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'))

You could use pandas.DataFrame.plot : 您可以使用pandas.DataFrame.plot

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

Output: 输出:

在此处输入图片说明


For learning purposes: 出于学习目的:

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

Output: 输出:

在此处输入图片说明

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

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