How to Display the Value of the Bar on Each Bar With Pyplot.Barh()

How to display the value of the bar on each bar with pyplot.barh()

Update: there's a built in method for this now! Scroll down a couple answers to "New in matplotlib 3.4.0".

If you can't upgrade that far, it doesn't take much code. Add:

for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')

result:

Sample Image

The y-values v are both the x-location and the string values for ax.text, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i is the y-location.

How to display the values on the bar plot for each bar with barh() in this case?

You should add is as matplotlib.axes.Axes.text.

If you have a plot like this:

import matplotlib.pyplot as plt


labels = ['A', 'B', 'C']
values = [150, 80, 10]


fig, ax = plt.subplots()

ax.barh(labels, values)

plt.show()

Sample Image

You can add labels with this loop (you may need to adjust x axis limits in order to fit labels):

for i, value in enumerate(values):
ax.text(value + 3, i, str(value))
xmin, xmax = ax.get_xlim()
ax.set_xlim(xmin, 1.1*xmax)

Sample Image

How to get barh plot with values displayed within each bar?

I think the error is coming from this line because ind = df_new['name'] makes ind a string, and you cannot add a number to it:

ax.set_yticks(ind+width/2)

You used enumerate(y) to place the text, but y is not declared in the code, so it must be something floating in the environment.

If I set up the data frame like this:

df_new = pd.DataFrame({'length':[13,14,5,10,16,17,8]},
index = ['U19','U17','U15','U13','U11','U9','U7'])
df_new.index.name = "name"

And call the horizontal plot with pandas.DataFrame.plot.bar it works fine:

fig, ax = plt.subplots()    
df_new.plot.barh(width=0.75,ax=ax)
ax.set_title('Title')
ax.set_xlabel('Anzahl')
ax.set_ylabel('Teams')
ax.set_xlim([0,20])
for i, v in enumerate(df_new['length']):
ax.text(x = v + 1, y = i + .1, s = str(v), color='blue', fontweight='bold')

Sample Image

Labeling horizontal bar using matplotlib bar_label

the issue is that the bar_label is a new feature and available in matplotlib version 3.4 or later - ref this link. Check the version of matplotlib using

import matplotlib 
print('matplotlib: {}'.format(matplotlib.__version__))

Upgrade to v3.4 or latest version using pip install matplotlib --upgrade. You will need to include the code in the link you provided and as mentioned by JohanC and be able to see bar labels

Display the value of the bar on each bar, wrong place

Update:

Version 3.4 of matplotlib added function bar_label, which could be incorporated as follows in the code below:

for bar_group in ax.containers:
ax.bar_label(bar_group, fmt='%.0f', size=18)

Old answer:

You can loop through the generated bars, and use their x, height and width to position the text. Adding an empty line into the string helps position the text independent of the scale. ax.margins() can add some space above the bars to make the text fit.

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({'Destiny': ['AJU','AJU','FOR','FOR','FOR' ],
'Flight':range(1501,1506),
'Year':[2019,2020,2019,2020,2019]})
ax = df.groupby(["Destiny","Year"])["Flight"].count().unstack().plot.bar(figsize=(12, 3))

for p in ax.patches:
x = p.get_x()
h = p.get_height()
w = p.get_width()
ax.annotate(f'{h:.0f}\n', (x + w/2, h), ha='center', va='center', size=18)
plt.margins(y=0.2)
plt.tight_layout()
plt.show()

example plot

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



Related Topics



Leave a reply



Submit