Search code examples
pandas

How to separate groups of stacked bars in pandas?


My input is this dataframe :

df = pd.DataFrame(
    {
        'ID': ['ID001', 'ID002', 'ID003'],
        'RUNNING': [5, 6, 3],
        'QUEUE': [1, 2, 5],
        'FINISHED': [6, 2, 4],
        'PROCESSED': [2, 6, 4],
    }
)

      ID  RUNNING  QUEUE  FINISHED  PROCESSED
0  ID001        5      1         6          2
1  ID002        6      2         2          6
2  ID003        3      5         4          4

I'm tring to make groups of stacked bars that separate the running and finished tasks for each id.

I made the code below but there is three problems :

  • the x ticks dont show the ids name
  • there is no space between each pair of stacked bars.
  • the graph is truncated from the left
running = df[['RUNNING', 'QUEUE']]
finished = df[['FINISHED', 'PROCESSED']]

fig, ax = plt.subplots(figsize=(7, 3))

running.plot(
    kind='bar',
    stacked=True,
    ax=ax,
    use_index=True,
    color={'RUNNING': 'orange', 'QUEUE': 'yellow'},
    edgecolor='black',
    position=1,
)
finished.plot(
    kind='bar',
    stacked=True,
    ax=ax,
    use_index=True,
    color={'FINISHED': 'green', 'PROCESSED': 'blue'},
    edgecolor='black',
    position=0,
)

fig.tight_layout()

plt.show()

enter image description here

I expect 3 groups (one group for each id) and each group will have two stacked bars.

Can you guys show me how to fix my code ?


Solution

  • You just need to modify the bar widths. They are too wide and overlap each other:

    # `color` param doesn't wok for me, maybe I have an older version of mpl
    ax = df[['RUNNING','QUEUE']].plot.bar(position=1,stacked=True, width=0.3, hatch='/')
    df[['FINISHED','PROCESSED']].plot.bar(position=0,stacked=True, ax=ax, width=0.3)
    

    Output:

    enter image description here