简体   繁体   English

Pandas - 绘制堆积条形图

[英]Pandas - Plotting a stacked Bar Chart

I am trying to create a stacked bar graph that replicates the picture, all my data is separate from that excel spreadsheet.我正在尝试创建一个复制图片的堆叠条形图,我的所有数据都与该 Excel 电子表格分开。

在此处输入图片说明

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)

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)

堆积条形图

那应该有帮助

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

Maybe you can use pandas crosstab function也许你可以使用熊猫交叉表功能

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

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

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))
from matplotlib import cm
cmap = cm.get_cmap('Spectral') # Colour map (there are many others)

df.plot(kind='bar', stacked=True, figsize=(20, 10), cmap=cmap, edgecolor='None')
plt.show()

This will also avoid duplicate colors in the legend of your bar chart.这也将避免在条形图的图例中出现重复的颜色。

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

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