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)
As of matplotlib 3.4.0, it's simplest to auto-label the bars with plt.bar_label
:
padding
to increase the distance between bars and labels (e.g., padding=20
)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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With