import matplotlib.pyplot as plt
import numpy as np
# 年龄分组
age_groups = ['<40', '40-49', '50-59', '60-69', '70+']
# 状态数据(只有3种状态)
state_data = {
0: [2.34, 4.26, 4.61, 3.01, 2.08], # 状态0
2: [78.91, 74.04, 73.78, 69.32, 64.98], # 状态2
4: [18.75, 21.7, 21.6, 27.67, 32.94] # 状态4
}
# 颜色配置(3种颜色)
colors = ['#4e79a7', '#e15759', '#59a14f']
state_labels = ['0', '1 and 2', '3 and 4']
# 设置图表
plt.figure(figsize=(12, 8))
bar_width = 0.25
x = np.arange(len(age_groups))
# 绘制分组柱状图并添加数值标签
for i, state in enumerate([0, 2, 4]):
# 绘制柱子
bars = plt.bar(x + i * bar_width,
state_data[state],
width=bar_width,
color=colors[i],
label=state_labels[i])
# 在每个柱子上方添加数值标签
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width() / 2.,
height + 0.5, # 在柱子顶部上方0.5单位处添加标签
f'{height:.1f}%', # 格式化显示一位小数
ha='center', va='bottom', fontsize=9)
# 添加标签和标题
plt.xlabel('Age (years)', fontsize=14, labelpad=15)
plt.ylabel('Proportion (%)', fontsize=14, labelpad=15)
plt.xticks(x + bar_width, age_groups, fontsize=12)
plt.yticks(fontsize=12)
# 设置Y轴范围,为数值标签留出空间
plt.ylim(0, max(max(state_data[0]), max(state_data[2]), max(state_data[4])) * 1.15)
# 添加图例(添加标题)
plt.legend(fontsize=12)
# 调整布局
plt.tight_layout()
plt.savefig('age_state_distribution.tiff', dpi=600, format='tiff',
bbox_inches='tight') # 确保标签完整保存
plt.show() 要无衬线字体