How to Add Value Labels on Bar Chart in Matplotlib
To add value labels on a bar chart in
matplotlib, use a loop over the bars and call ax.text() to place the label above each bar. This method lets you display the height or value of each bar clearly on the chart.Syntax
Use ax.text(x, y, label) inside a loop over bars to add labels. Here:
axis the axes object.xis the horizontal position of the label (usually the bar center).yis the vertical position (usually the bar height).labelis the text to display (e.g., the bar height).
python
for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2, height, f'{height}', ha='center', va='bottom')
Example
This example creates a simple bar chart and adds value labels on top of each bar showing their heights.
python
import matplotlib.pyplot as plt values = [5, 7, 3, 8] categories = ['A', 'B', 'C', 'D'] fig, ax = plt.subplots() bars = ax.bar(categories, values) for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2, height, f'{height}', ha='center', va='bottom') plt.show()
Output
A bar chart with four bars labeled 5, 7, 3, and 8 above each bar respectively.
Common Pitfalls
Common mistakes include placing labels inside the bars where they are hard to read or forgetting to center the text horizontally. Also, not adjusting the vertical position can cause labels to overlap the bars or be cut off.
Always use ha='center' to center labels horizontally and va='bottom' to place them just above the bar.
python
import matplotlib.pyplot as plt values = [4, 6, 2] categories = ['X', 'Y', 'Z'] fig, ax = plt.subplots() bars = ax.bar(categories, values) # Wrong: labels inside bars, not centered for bar in bars: height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2, height / 2, f'{height}') # Not centered, inside bar plt.show()
Output
A bar chart with labels placed at the center inside each bar, making them hard to read.
Quick Reference
- Use
ax.text()to add labels. - Calculate label x-position as
bar.get_x() + bar.get_width() / 2. - Set vertical position to bar height.
- Use
ha='center'andva='bottom'for good label placement.
Key Takeaways
Use a loop over bars and
ax.text() to add value labels on bar charts.Center labels horizontally with
ha='center' and place them just above bars with va='bottom'.Calculate label positions using bar x-position plus half the bar width and the bar height.
Avoid placing labels inside bars without centering as it reduces readability.
Adding value labels helps make bar charts easier to understand at a glance.