0

I need to display the values above their respective bars. Can't quite figure it out. I have been trying for loops, and was told to possibly use patches but I'm pretty new at this still and having some trouble. Help would be appreciated! The pictures include the short bit of code from the jupyter notebook.

Here is the pseudocode

df=read_csv
df.sort_values
df = df/2233*100.round

ax=df.plot(bar)
ax.set_title
ax.tick_params
ax.legend

for i, value in enumerate(df):
    label=str(value)
    ax.annotate(label, xy=(i, value))

First step

Second step

The actual code I try,

for i, value in enumerate(df_dstopics):
    label = str(value)
    ax.annotate(label, xy=(i, value))
clarkin16
  • 1
  • 1
  • 4
  • Does this answer your question? [python - how to show values on top of bar plot](https://stackoverflow.com/questions/53066633/python-how-to-show-values-on-top-of-bar-plot) – bigbounty Jul 29 '20 at 04:58

1 Answers1

2

Parameter xy in ax.annotate() needs to be a tuple which represents a point in coordinate system. However, the value in your for i, value in enumerate(df) is column name, which is definitely not a valid constant.

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

df = pd.DataFrame({'Very interested':np.random.rand(2), 'Somewhat interested':np.random.rand(2)+1, 'Not interested':np.random.rand(2)+2})

ax = df.plot(kind='bar', color=['r','b','g']) 

for p in ax.patches:
    ax.annotate(s=np.round(p.get_height(), decimals=2),
                xy=(p.get_x()+p.get_width()/2., p.get_height()),
                ha='center',
                va='center',
                xytext=(0, 10),
                textcoords='offset points')

plt.show()

enter image description here

Reference:

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52