简体   繁体   中英

draw a grouped bar graph from a dataframe originated from an sql query grouped on multiple attributes

I'm relatively new to pandas and numpy

what I'm trying to achieve is:

  • starting from a dataframe that originated from an sql query that groups errors by a tag_name (defining the type of task is originating it), the error message and the occurrences of that particular error for the specific meta-tag
  • build a grouped bar graph in which every group in the x axis represents a meta-tag, while each bar is an error message and the bar height determined by the number of occurrences

Following there is a sample dataframe:

        name                                           message  occurred
0  meta-tag1                                       InvalidPlan         1
1  meta-tag1  Maximun number of attempts at planning surpassed       276
2  meta-tag1                               Rescheduling worker       275
3  meta-tag2                                       InvalidPlan        18
4  meta-tag3  Maximun number of attempts at planning surpassed        22

I can't seem to find a solution that allows me to produce the result I want.

At first I used np.unique to build 2 lists containing the unique meta-tags and unique error

Then generating a list of dataframes filtered for meta-tag, then generating an array from each sub-dataframe containing only the occurences per error and I tried feeding to a pyplot feeding it the list of arrays with the occurrencies, the unique error-messages as columns and unique meta-tags as index, but I couldn't get it working and I am pretty sure it's the wrong approach at it.

I'm pretty sure it can be achieved only by manipulating the dataframe in the correct way, which it's pretty hard for me at my current level, any suggestion is really really welcome.

I think this is what you want: Let's call your data frame df

t=df.groupby(['name', 'message'])['occurred'].sum().unstack('message').fillna(0)

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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