Python Pandas - 绘制堆积条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23415500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:56:22  来源:igfitidea点击:

Pandas - Plotting a stacked Bar Chart

pythonmatplotlibpandasipython-notebookpython-3.4

提问by Kuzen

I am trying to create a stacked bar graph that replicates the picture, all my data is separate from that excel spreadsheet.

我正在尝试创建一个复制图片的堆叠条形图,我的所有数据都与该 Excel 电子表格分开。

enter image description here

在此处输入图片说明

I cant figure out how to make a dataframe for it like pictured, nor can I figure out how to make the stacked bar chart. All examples I locate work in different ways to what I'm trying to create.

我无法弄清楚如何为它制作如图所示的数据框,也无法弄清楚如何制作堆积条形图。我找到的所有示例都以与我尝试创建的方式不同的方式工作。

My dataframe is a csv of all values narrowed down to the following with a pandas dataframe.

我的数据框是一个包含所有值的 csv,使用 Pandas 数据框缩小到以下值。

      Site Name    Abuse/NFF
0    NORTH ACTON       ABUSE
1    WASHINGTON         -
2    WASHINGTON        NFF
3    BELFAST            -
4    CROYDON            - 

I have managed to count the data with totals and get individual counts for each site, I just cant seem to combine it in a way to graph.

我已经设法用总数计算数据并获得每个站点的单独计数,我似乎无法将它组合成图表。

Would really appreciate some strong guidance.

真的很感激一些强有力的指导。

Completed code, many thanks for the assistance completing.

完成代码,非常感谢帮助完成。

test5 = faultdf.groupby(['Site Name', 'Abuse/NFF'])['Site Name'].count().unstack('Abuse/NFF').fillna(0)

test5.plot(kind='bar', stacked=True)

采纳答案by chucklukowski

Are you getting errors, or just not sure where to start?

您是否遇到错误,或者只是不确定从哪里开始?

%pylab inline
import pandas as pd
import matplotlib.pyplot as plt

df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)

stacked bar plot

堆积条形图

回答by Domino

That should help

那应该有帮助

df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)

回答by Rafael Jose Gonzlez de Gouveia

Maybe you can use pandas crosstab function

也许你可以使用熊猫交叉表功能

test5 = pd.crosstab(index=faultdf['Site Name'], columns=faultdf[''Abuse/NFF''])

test5.plot(kind='bar', stacked=True)

回答by kamran kausar

If you want to change the size of plot the use arg figsize

如果要更改绘图的大小,请使用 arg figsize

df.groupby(['NFF', 'ABUSE']).size().unstack()
      .plot(kind='bar', stacked=True, figsize=(15, 5))