python - how to show values on top of bar plot

Simply add

for i, v in enumerate(y):
    plt.text(xlocs[i] - 0.25, v + 0.01, str(v))

before plt.show(). You can adjust the centralization or height of the text by changing the (-0.25) and (0.01) values, respectively.

New plot


plt.text() will allow you to add text to your chart. It only enables you to add text to one set of coordinates at a time, so you'll need to loop through the data to add text for each bar.

Below are the main adjustments I made to your code:

# assign your bars to a variable so their attributes can be accessed
bars = plt.bar(x, height=y, width=.4)

# access the bar attributes to place the text in the appropriate location
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x(), yval + .005, yval)

I added .005 to the y-value so that the text would be placed above the bar. This can be modified to obtain the appearance you are looking for.

Below is a full working example based on the original code. I made a few modifications to make it less brittle as well:

import matplotlib.pyplot as plt

# set the initial x-values to what you are wanting to plot
x=[i/2 for i in range(10)]
y=[0.95,
0.95,
0.89,
0.8,
0.74,
0.65,
0.59,
0.51,
0.5,
0.48]

bars = plt.bar(x, height=y, width=.4)

xlocs, xlabs = plt.xticks()

# reference x so you don't need to change the range each time x changes
xlocs=[i for i in x]
xlabs=[i for i in x]

plt.xlabel('Max Sigma')
plt.ylabel('Test Accuracy')
plt.xticks(xlocs, xlabs)

for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x(), yval + .005, yval)

plt.show()