How to annotate pandas bar graph with values from two dictionaries displayed on one graph?

Viewed 106

My Code:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ME_Requests = {'John Doe': 105, 'Amanda Doe': 64, 'Maria Doe': 48, 'Dimitrii Doe': 44}
non_ME_Requests = {'John Doe': 47, 'Amanda Doe': 27, 'Maria Doe': 26,}

df = pd.DataFrame({'ME_Request':ME_Requests,
          'non_ME_request':non_ME_Requests})
          

axes = df.plot.bar( title='My Barplots',subplots = True, sharex=True, sharey=True)
for ax in axes:
    for p in ax.patches:
        ax.annotate(str(round(p.get_height(),2)), (p.get_x(), p.get_height()))

plt.gcf().autofmt_xdate()
plt.show()

It returns two separate bar graphs (blue and orange) with annotations. However, I'm aiming to have both (blue and orange) showing on the same graph. Also, not sure why orange graph has numbers displayed in different format example: 0.0 instead of 0.

enter image description here

Could someone help me with this please? Thank you in advance!

1 Answers

You are passing subplots=True to the plotting function, which is why it is creating two subplots instead of putting both sets of bars on the same axes.

If you use subplots=False, then the function only returns one axes and not an array, so you need to remove the for-loop

ax = df.plot.bar( title='My Barplots',subplots = False, sharex=True, sharey=True)
for p in ax.patches:
    ax.annotate('{:.0f}'.format(p.get_height()), (p.get_x(), p.get_height()))
Related