Учитывая pandas df, я хочу создать гистограммы с накоплением, где все значения в строке сложены в каждом столбце. Я хочу, чтобы xticks были номером индекса, а значение y было суммой сложенных столбцов каждой строки. Однако я не смог этого добиться.
Я получаю TypeError: только массивы размера 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'))






Вы можете использовать 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))
Выход: