Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save StuffbyYuki/f85181dae148c860a9cb559732facb07 to your computer and use it in GitHub Desktop.
Save StuffbyYuki/f85181dae148c860a9cb559732facb07 to your computer and use it in GitHub Desktop.
Python:Matplotlib - Add labels on bar chart
def autolabel(rects, xpos='center'):
"""
Attach a text label above each bar in *rects*, displaying its height.
*xpos* indicates which side to place the text w.r.t. the center of
the bar. It can be one of the following {'center', 'right', 'left'}.
"""
xpos = xpos.lower() # normalize the case of the parameter
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} # x_txt = x + w*off
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
'{}'.format(height), ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment