-1

I have a Dataframe as given below

df = pd.DataFrame(
{
    'Dates': ['2021-04-11', '2021-06-08', '2021-06-08', '2021-06-09', '2021-06-10', '2021-07-18', '2021-07-18'], 
    'Results': ['Negative', 'Invalid', 'Negative','Negative','Negative', 'Negative', 'Positive' ], 
    'Size': [1, 1, 1, 1, 4, 21, 2]
    
})

I want to plot a subdivided bar graph as shown below in the given picture. [![enter image description here][1]][1]

I have been stuck on this for a while now. Tried using groupby(), sum(), size() etc, but could not figure it.

Any help is greatly appreciated.

Thanks. [1]: https://i.stack.imgur.com/HrKRY.jpg

  • Does this answer your question? [Pandas - Plotting a stacked Bar Chart](https://stackoverflow.com/questions/23415500/pandas-plotting-a-stacked-bar-chart) – ifly6 Jul 21 '21 at 18:34
  • @ifly6 It doesn't. There the data is separated into columns wheres in my case, the data is present in a single column and it's categorical as well. Although it doesn't solve my question, I will try to get the idea out of this. – shiva kumar Jul 21 '21 at 18:37
  • index on results then unstack. poof, you have your data separated into columns. it's even in the answer there: `df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF')` – ifly6 Jul 21 '21 at 18:40
  • @ifly6 In my Dataframe, I need the 'size' column which gives the number of count each result occurred on that day. So, I cannot be using the count() function as given above – shiva kumar Jul 21 '21 at 18:51
  • yea so don't write the _exact_ same code, adapt the code there, set indices and unstack – ifly6 Jul 21 '21 at 18:53

1 Answers1

0

Just reshape it by setting indices on date and results, then unstacking Results. After that, plot.

df.set_index(['Dates', 'Results']).sort_index(0).unstack().plot.bar(stacked=True)

enter image description here

If you don't want it with a column multi-index, and instead want "Invalid", "Negative", "Positive", just create an intermediate data frame from the unstack (I'll call it temp) and assign temp.columns = temp.columns.get_level_values(1). Then call temp.plot.bar(stacked=True).


To specify size using the OOP matplotlib interface:

f, ax = plt.subplots(figsize=(HEIGHT, WIDTH))
temp.plot.bar(ax=ax, stacked=True)

Save the figure to file using f.savefig(PATH).

ifly6
  • 5,003
  • 2
  • 24
  • 47
  • Thanks for the detailed explanation. I understand it now. One more thing, is there a way to increase the size of the chart displayed? The graph displayed has many dates and its cramped in the default size. Thank you. – shiva kumar Jul 21 '21 at 19:20
  • See edit. tl;dr is to set figure size with `figsize`. – ifly6 Jul 21 '21 at 19:24
  • Thanks a lot. I am very new to graphs and hence these silly questions. Thank you – shiva kumar Jul 21 '21 at 19:29