2

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
  • 36,675
  • 19
  • 86
  • 83
asif abdullah
  • 250
  • 3
  • 16
  • 1
    As per this [answer](https://stackoverflow.com/a/67561982/7758804) of the duplicate, which thoroughly covers [`.bar_label`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar_label.html), `ax.bar_label(..., padding=3)` – Trenton McKinney Dec 27 '22 at 19:54

1 Answers1

7

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
  • 36,675
  • 19
  • 86
  • 83