Python newbie here. I want to show values above each bin in the following graph:
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:
Call matplotlib. pyplot. barh(x, height) with x as a list of bar names and height as a list of bar values to create a bar chart. Use the syntax “for index, value in enumerate(iterable)” with iterable as the list of bar values to access each index, value pair in iterable.
Click the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option. Note: The options will differ depending on your chart type. If you want to show your data label inside a text bubble shape, click Data Callout.
Just call the plot() function and provide your x and y values. Calling the show() function outputs the plot visually.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With