Skip to content

Instantly share code, notes, and snippets.

@pashri
Created January 6, 2021 23:20
Show Gist options
  • Save pashri/aaa8cced59073346ec5c5e941c509c17 to your computer and use it in GitHub Desktop.
Save pashri/aaa8cced59073346ec5c5e941c509c17 to your computer and use it in GitHub Desktop.
Add value labels to the bars in a bar chart
import pandas as pd
import matplotlib as mpl
def label_bar(
s: pd.Series,
horizontal: bool = False,
**kwargs
) -> mpl.axes.Axes:
"""Creates a Matplotlib bar chart with values in the bars
from a Pandas Series."""
if horizontal:
ax = s.plot.barh(**kwargs)
offset = ax.get_ylim()[1] / 10
else:
ax = s.plot.bar(**kwargs)
offset = ax.get_xlim()[1] / 10
rects = ax.patches
for rect in rects:
height = rect.get_height()
width = rect.get_width()
x = rect.get_x()
y = rect.get_y()
if horizontal:
label = str(width)
ax.text(width + offset, y + height/2, label, ha='left', va='center')
else:
label = str(height)
ax.text(x + width/2, height + offset, label, ha='center', va='bottom')
return ax
# Example
ax = df['column_1'].value_counts().pipe(label_bar, horizontal=True, figsize=(12, 9))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment