Created
April 27, 2020 00:41
-
-
Save StuffbyYuki/f85181dae148c860a9cb559732facb07 to your computer and use it in GitHub Desktop.
Python:Matplotlib - Add labels on bar chart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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