Как отобразить значения на колонках в диаграмме matplotlib?
Пытаюсь выровнять значения на колонках инвертированной диаграммы, но не получается, с правой всё получилось, а вот как с левой быть не знаю
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
fig, axes = plt.subplots(1,2, sharey=True, figsize=(9, 6))
plt.suptitle('Повозрастная диаграмма по годам')
axes[0].barh(male_female_df['years'], male_female_df['male'])
axes[0].axis(xmin = 60, xmax = 80)
axes[0].invert_xaxis()
axes[0].set(title='Мужчины')
rects_male = axes[0].patches
for rect in rects_male:
# Get X and Y placement of label from rect
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label; change to your liking
space = -130
# Vertical alignment for positive values
ha = 'right'
# Use X value as label and format number
label = '{:,.1f}'.format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at bar end
xytext=(space, 0), # Horizontally shift label by `space`
textcoords='offset points', # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha, # Horizontally align label differently for positive and negative values
color = 'black')
axes[1].barh(male_female_df['years'], male_female_df['female'], color='hotpink')
axes[1].axis(xmin = 60, xmax = 80)
axes[1].set(title='Женщины')
axes[1].xaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
rects_female = axes[1].patches
# Place a label for each bar
for rect in rects_female:
# Get X and Y placement of label from rect
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label; change to your liking
space = -30
# Vertical alignment for positive values
ha = 'left'
# Use X value as label and format number
label = '{:,.1f}'.format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at bar end
xytext=(space, 0), # Horizontally shift label by `space`
textcoords='offset points', # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha, # Horizontally align label differently for positive and negative values
color = 'black')
plt.show()
Источник: Stack Overflow на русском