1

The space between the plot and the values (204 kwh, 604 kwh, 60 kwh) is too little. How can I move these values a bit higher and increase the spacing?

What I have:

What I want:

Code:

x_name = ['Average\nneighborhood\u00b9', 'Your\nconsumption', 'Efficient\nneighborhood\u00b2']
plt.figure(facecolor='#E2EBF3')
fig = plt.figure(figsize=(12,10))
plt.bar(x_name, val, color =['cornflowerblue', 'saddlebrown', '#196553'],width = .8)
plt.margins(x = .1 , y = 0.25)

plt.xticks(fontsize=25)
plt.yticks([])
 
hfont = {'fontfamily':'serif'}

for index, value in enumerate(np.round(val,2)):
  plt.text(index,value, str(value)+" kWh",fontsize=25, ha='center', va = 'bottom',**hfont)
tdy
  • 26,545
  • 9
  • 43
  • 50
asif abdullah
  • 210
  • 2
  • 11
  • 2
    Your post is missing essential code, making it impossible to know what should changed. It also would be helpful to add some reproducible test data. Depending on how you created the plot and added the text, you might try to append a newline (`123.12 kWh\n` ?) to the strings. – JohanC Jan 24 '22 at 13:44
  • just put the text a bit higher, for instance `plt.text(index,value+50, ...`. – Stef Jan 24 '22 at 15:39

1 Answers1

4

As of matplotlib 3.4.0, it's simplest to auto-label the bars with plt.bar_label:

  • Set padding to increase the distance between bars and labels (e.g., padding=20)
  • Set fmt to define the format string (e.g., fmt='%g kWh' adds "kWh" suffix)
bars = plt.bar(x_name, val)                   # store the bar container
plt.bar_label(bars, padding=20, fmt='%g kWh') # auto-label with padding and fmt

Note that there is an ax.bar_label counterpart, which is particularly useful for stacked/grouped bar charts because we can iterate all the containers via ax.containers:

fig, ax = plt.subplots()
ax.bar(x_name, val1, label='Group 1')
ax.bar(x_name, val2, label='Group 2', bottom=val1)
ax.bar(x_name, val3, label='Group 3', bottom=val2)

# auto-label all 3 bar containers
for c in ax.containers:
    ax.bar_label(c)
tdy
  • 26,545
  • 9
  • 43
  • 50