28

Python newbie here. I want to show values above each bin in the following graph:

bar chart

This is my code:

x=[i for i in range(1,11)]
y=[0.95,
0.95,
0.89,
0.8,
0.74,
0.65,
0.59,
0.51,
0.5,
0.48]

plt.bar(x, height= y)
xlocs, xlabs = plt.xticks()
xlocs=[i+1 for i in range(0,10)]
xlabs=[i/2 for i in range(0,10)]
plt.xlabel('Max Sigma')
plt.ylabel('Test Accuracy')
plt.xticks(xlocs, xlabs)
plt.show()

this is the graph that I want:

bar chart

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Dan
  • 313
  • 1
  • 3
  • 9
  • @Dan, If this is not a duplicate, you need to tell us why not by showing your research. –  Oct 30 '18 at 14:54
  • 1
    i saw the other comment and i wasn't able to do it with my code – Dan Oct 30 '18 at 17:57

3 Answers3

43

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

Maroca
  • 544
  • 5
  • 4
25

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()
daronjp
  • 684
  • 8
  • 9
-1

Try:

plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True This makes it simple