Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positioning of multiple stacked bar plot with pandas

I am trying to make a multiple stacked bar plot with pandas.

Here is a sample code:

import pandas as pd

df = pd.DataFrame({'a':[10, 20], 'b': [15, 25], 'c': [35, 40], 'd':[45, 50]}, index=['john', 'bob'])

ax = df[['a', 'c']].plot.bar(position=0, width=0.1, stacked=True)
df[['b', 'd']].plot.bar(position=1, width=0.1, stacked=True, ax=ax)

Which, in a notebook, give the following output: stacked bar plot

The problem I'm facing is that, for each group, the bars are not in the order I want them to be. The doc says that the "position" argument for a bar plot specifies the relative position of the bar, with 0 being left and 1 being right. But it seems to do the complete opposite. What am I misunderstanding?

like image 790
fireboot Avatar asked Oct 20 '25 15:10

fireboot


1 Answers

The position parameter in pd.Df.plotcontrols the alignment of your bar plot layouts. It resembles similarity with the align parameter of a matplotlib bar plot.

Illustrations:

1. when position=0.5: [Default : center alignment]

df[['a', 'c']].plot.bar(position=0.5, width=0.1, stacked=True, ax=ax)
df[['b', 'd']].plot.bar(position=0.5, width=0.1, stacked=True, ax=ax)

The bars are coinciding with the X-axis labels as shown: enter image description here 2. when position=0:[left/bottom edge alignment]

df[['a', 'c']].plot.bar(position=0, width=0.1, stacked=True, ax=ax)
df[['b', 'd']].plot.bar(position=0, width=0.1, stacked=True, ax=ax)

The left most portion of the bars are coinciding with the X-axis labels as shown: enter image description here

Now, you can clearly distinguish the difference between the above 2 figures.

like image 134
Nickil Maveli Avatar answered Oct 23 '25 06:10

Nickil Maveli