Skip to content Skip to sidebar Skip to footer

Annotating Bar Chart In Pandas

I have a bar chart that displays 2 bars one for 2015 and one for 2016. x axis shows drug name y axis shows amount prescribed I would like to display annotation on the bars just

Solution 1:

Do you think that this can help:

import pandas as pd
df = pd.DataFrame({"date_x":[2015]*5,
                   "Occurance_x":[2994, 2543, 2307, 1535, 1511],
                   "VTM_NM":["Not Specified", "Mesalazine", "Omeprazole",
                             "Esomeprazole", "Lansoprazole"],
                   "date_y":[2016]*5,
                   "Occurance_y":[3212, 2397, 2370, 1516, 1547]})

ax = df[["VTM_NM","Occurance_x", "Occurance_y"]].plot(x='VTM_NM', 
                                                      kind='bar', 
                                                      color=["g","b"],
                                                      rot=45)
ax.legend(["2015", "2016"]);
for patch in ax.patches:
    bl = patch.get_xy()
    x = 0.5 * patch.get_width() + bl[0]
    # change 0.92 to move the text up and down
    y = 0.92 * patch.get_height() + bl[1] 
    ax.text(x,y,"%d" %(patch.get_height()),
            ha='center', rotation='vertical', weight = 'bold')

plot

Edit

If you then want a nicer style you can add this at the beginning

from matplotlib import pyplot as plt
plt.style.use('fivethirtyeight')

and modify ax.legend(["2015", "2016"]) with ax.legend(["2015", "2016"], frameon=False). For a full list of style type plt.style.available

Solution 2:

Try moving the first two lines to just before plt.show(). The current code references ax before defining it.

Post a Comment for "Annotating Bar Chart In Pandas"