0

I have a df like:

name  year  total packets
pak   2016  4
pak   2018  18
pak   2022  5
ind   2019  10
ind   2021  9
afg   2017  2
afg   2018  32
afg   2022  31

I need to draw a stacked-bar graph that shows each name on x-axis and the year on y-axis with total packets labeled within the stack bar for each name. Something like the answer here: Python: Stacked bar plot based on values from multiple columns within the same DF

I tried something like:

        temp_df = pd.DataFrame()

        # group by each column counting the size of each category values
        for col in old_df:
            grped = old_df.groupby(col).size()
            grped = grped.rename(grped.index.name)
            temp_df = temp_df.merge(grped.to_frame(), how='outer', left_index=True, right_index=True)

        # plot the merged dataframe
        temp_df.plot.bar(stacked=True)
Jlow
  • 17
  • 5
  • Do you try pivoting and not working for you? – jezrael Jan 19 '23 at 13:50
  • `df.pivot_table(index="name", columns='year', values='packets', aggfunc='sum').plot(kind='bar', stacked=True)` – jezrael Jan 19 '23 at 13:51
  • @jezrael this gives the sum on the y-axis, I need the year on y-axis and the sum of packects labeled in side the bar chunk for each year – Jlow Jan 19 '23 at 13:59

0 Answers0