绘制一系列条形图,并将其余条形图组合成一个条形图

时间:2019-10-03 23:16:28

标签: pandas matplotlib

想象一下,我的列中的列具有各种不同的值,例如:

msiexec /i $installer.fullname

我想使用matplotlib.pyplot绘制条形图,该条形图将显示出现在系列中的数字值A,B,C和OTHERS。通过这样做,我设法在没有“其他”分组的情况下做到了这一点:

COL1    FREQUENCY
A       30
B       20
C       50
D       10
E       15
F       5

ax = srs.plot.bar(rot=0)

我知道它会显示所有条形图,如何将其限制为仅显示A,B,C和OTHERS的条形图?

2 个答案:

答案 0 :(得分:2)

您可以先执行map,然后再执行groupby.sum()

s = df['COL1'].map(lambda x: x if x in ('A','B','C') else 'OTHERS')
to_plot = df.FREQUENCY.groupby(s).sum()
to_plot.plot.bar()

输出:

https://cryptography.io/en/latest/installation/#static-wheels

答案 1 :(得分:0)

您需要创建一个新的数据框并在其后进行绘制

# list all values you want to keep
col1_to_keep = ['A','B','C']
# create a new dataframe with only these values in COL1
srs2 = srs.loc[srs['COL1'].isin(col1_to_keep)]
# create a third dataframe with only what you dont want to keep
srs3 = srs.loc[~srs['COL1'].isin(col1_to_keep)]
# create a dataframe with only one row containing the sum of frequency
rest = pd.DataFrame({'COL1':["OTHER"],'FREQUENCY': srs3['FREQUENCY'].sum()})
# add this row to srs2
srs2 =srs2.append(rest)
# you can finally plot it
ax = srs2.plot.bar(rot=0)