简体   繁体   中英

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

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.

在此处输入图片说明

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

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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM