1

I have some code to open an excel file as dataframe. Based on this, a barh is plotted. However, I 'am unable to show the values in the bars. The excel has column headers which are changing from file to file which are shown in the legend.

the dataframe looks like this:

    40+     50+     60+
e   .35     .45     .28
n   .28     .52     .27

tried ax.annotate

many thanks

"""code"""

import pandas as pd
import numpy as np
from pandas import ExcelWriter
from pandas import ExcelFile
df = pd.read_excel('C://1/table/c.xlsx', sheet_name='Sheet1')

print (df)

ax = df.plot.barh(width=0.9, fontsize='xx-large', figsize=(20,20), color=      
['#a6979C', '#BFB0BA', '#D9CCD9', '#bebabf', '#eae4f2'] )

ax.legend(bbox_to_anchor=(1,1),loc='best', fontsize='30')

expected result: Horizontal bars with the values in the bars

NicoDW875
  • 15
  • 5
  • Hey Nico, please see [How to ask a good pandas question](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and please format your code. No one here knows what your xlsx file looks like, or your expected output. Downvoting until you improve the quality of the post. – Umar.H Oct 11 '19 at 11:24
  • Sorry, didn't notice it. fixed it – NicoDW875 Oct 11 '19 at 14:52

1 Answers1

1

I copied your code, adding ";" after both instructions and got the proper result (just horizontal bars), using Jupyter Notebook.

So probably you should add semicolons.

To add values on bars

I changed a little numerical values and added superimposing of values on each bar, annotating them the following way:

ax = df.plot.barh(width=0.7, fontsize='16', figsize=(11,5));
ax.legend(bbox_to_anchor=(1, 0.3), fontsize='14');
for p in ax.patches:
    w = p.get_width()
    ax.annotate(f'{w:.2f}', (w * 0.5, p.get_y() + 0.1))

Experiment in your environment, adjusting various numerical parameters as you deem appropriate.

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Thanks Valdi_Bo.That worked great. Was already in Jupyter but didn't know that semicolons were that necessary. – NicoDW875 Oct 12 '19 at 09:44