绘制多级groupby datafram条形图

2024-06-16 09:54:42 发布

您现在位置:Python中文网/ 问答频道 /正文

使用groupby方法

    df = Al[['Connection Name','UAS-RS', 'SES-RS', 'OFS-RS', 'ES-RS', 'BBE-RS', 'Date', 'Alarm Type']]
    cols = ['Connection Name', 'Date', 'Alarm Type']

    df.mask(df == 0, np.nan).groupby(cols)[['UAS-RS', 'SES-RS', 'OFS-RS', 'ES-RS', 'BBE-RS']].count()

我得到了下表: table

最初的表有这样的结构:

       | ConName |   Date   | Alarm | ETH1 | ETH2 | ETH 3|
       | AR21    | 25-01-19 |  AL1  |   1  |   0  |   3  |  
       | AR22    | 25-01-19 |  AL2  |   0  |   0  |   1  |
       | AR23    | 26-01-19 |  AL1  |   1  |   1  |   0  |  
       | AR21    | 26-01-19 |  AL2  |   0  |   1  |   0  |  

问题

我想为每个连接名构建条形图,描述两种报警类型之间的特性分布

我得到的:

res

所需输出:

out

我的上一个代码只为一个连接名构建绘图:

for date in df[df['Connection Name']=='AR-CY18 A2.5G-RTA33']['Date']:
    df.mask(df == 0, np.nan).groupby('Alarm Type')[['UAS-RS', 'SES-RS', 'OFS-RS', 'ES-RS', 'BBE-RS']].count().plot(kind='bar',stacked=True,subplots=True)

另外,问题是,脚本按日期构建多个具有相同输出的绘图(我在第77个绘图上中断了内核)

我做错什么了?取消堆叠(unstack().plot.barh())也没有帮助

欢迎提供任何线索


Tags: name绘图dfdateestypeuasconnection
1条回答
网友
1楼 · 发布于 2024-06-16 09:54:42

看起来您正试图为每个(date, conName)生成一个图。我会这么做:

for (dt, con), d in df.groupby(['Date','ConName'], group_keys=False):
    fig,ax = plt.subplots()
    d.groupby('Alarm')[['ETH1','ETH2']].count().plot.bar(ax=ax)
    ax.set_title(con)

输出将是这样的几个图,其中2conName

enter image description here

相关问题 更多 >