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:
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()
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)
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')
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()
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.
Related Topics
Parsing Outlook .Msg Files With Python
Sum a Column Based on Groupby and Condition
How to Convert a List of Dictionaries to Json in Python/Django
Calculate Sklearn.Roc_Auc_Score for Multi-Class
Python Login Script; Usernames and Passwords in a Separate File
How to Tell Python to Convert Integers into Words
Unit Testing a Method With No Return Value
Number of Common Letters in Two Strings
How to Generate and Open an Outlook Email With Python (But Do Not Send)
Removing Punctuations and Spaces in a String Without Using Regex
How to Add a Delay to Message.Delete()
Faster Way to Read Excel Files to Pandas Dataframe
Python: Split a List into Multiple Lists Based on a Subset of Elements
Python: Using Doctests for Classes
Python/Pandas: How to Match List of Strings With a Dataframe Column