0

I am plotting some bars and I would like to center the text (y-values) on top of each bar. So far I have this code (with this answer as reference):

import matplotlib.pyplot as plt
import numpy as np
from operator import add

colors =['#6C8EBF', '#82B366', '#D79B00', '#B85450', '#9673A6'];

resolution = [1, 2, 3, 4, 5, 6];
resolution_labels = ['640x480', '800x600','960x720', '1024x768', '1280x720 (720p)', '1920x1080 (1080p)'];
latency = [5.06, 10, 12, 14, 15, 17]

plt.figure(1)
plt.xticks(resolution, resolution_labels, rotation=45)
plt.bar(resolution, latency, color=colors[0], width=0.5, align='center')
plt.axis();
plt.xlabel('Resolutions');
plt.ylabel('Latency [ms]');
axes = plt.gca()
axes.yaxis.grid()
for i, v in enumerate(latency):
    plt.text(i+0.8, latency[i] + .25, str(v)+"ms", color=colors[0], fontweight='bold')
plt.show()

How can I also plot each label on the center of the bar? Thanks for the help

aripod
  • 55
  • 1
  • 14
  • 1
    `plt.text(i+1, v, str(v)+"ms\n", color=colors[0], fontweight='bold', ha='center', va='center')` – JohanC Jul 25 '20 at 13:37
  • That didn't work. Printed the labels to the left of the bars and the last one even outside the plot. i+1.5 was too far so the one that worked was `plt.text(i+1.5, v, str(v)+"ms\n", color=colors[0], fontweight='bold', ha='center', va='center')` – aripod Jul 25 '20 at 13:39
  • Yes, we answered at the same time. Fixed. Thanks for the help – aripod Jul 25 '20 at 13:41
  • `plt.tight_layout()` just before `plt.show()` would fit the labels into the plot – JohanC Jul 25 '20 at 13:46

0 Answers0