基于Python利用最值与均值绘制分性别指标的极值均值图
实现极值均值图的绘制
由于仅拥有min、max和avg统计值,无法生成依赖原始数据的传统箱线图,我们可以用Matplotlib手动绘制垂直线连接极值,并用标记点标注均值,还原Excel风格的极值均值图。
实现步骤与代码
- 导入所需库
import pandas as pd import matplotlib.pyplot as plt
- 加载数据集
data = [['Male', 'Height', 160.0, 170.0, 165.0], ['Male', 'Weight', 70.0, 80.0, 75.0], ['Female', 'Height', 150.0, 160.0, 155.0], ['Female', 'Weight', 50.0, 60.0, 55.0], ] df = pd.DataFrame(data, columns=["gender", "metric", "min", "max", "avg"])
- 绘制极值均值图(基础版)
我们将每个「性别-指标」组合作为x轴独立类别,用不同颜色区分性别:
# 定义x轴位置、标签与性别配色 x_labels = [] x_positions = [] pos = 0 gender_colors = {'Male': '#1f77b4', 'Female': '#ff7f0e'} metrics = df['metric'].unique() # 为每个性别-指标组合分配x轴位置 for metric in metrics: for gender in df['gender'].unique(): x_labels.append(f"{gender}\n{metric}") x_positions.append(pos) pos += 1 # 创建绘图对象 plt.figure(figsize=(8, 6)) # 遍历数据绘制垂直线与均值点 for idx, row in df.iterrows(): x = x_positions[idx] # 绘制min到max的垂直线 plt.plot([x, x], [row['min'], row['max']], color=gender_colors[row['gender']], linewidth=2) # 绘制均值标记点(仅在首次出现性别时添加图例标签) plt.scatter(x, row['avg'], color=gender_colors[row['gender']], s=100, zorder=5, label=row['gender'] if idx in [0, 2] else "") # 配置图表样式 plt.xticks(x_positions, x_labels) plt.ylabel('数值') plt.title('不同性别各指标的极值与均值分布') plt.legend(title='性别') plt.grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout() plt.show()
进阶:按指标分组对比
如果需要将同一指标的男女数据并排展示,可调整x轴位置分配逻辑:
plt.figure(figsize=(8, 6)) # 按指标分组的x轴配置 x_labels = metrics x_base_positions = [i * 1.5 for i in range(len(metrics))] # 组间距设为1.5 gender_order = ['Male', 'Female'] # 遍历数据绘图 for idx, row in df.iterrows(): metric_idx = list(metrics).index(row['metric']) gender_idx = gender_order.index(row['gender']) x = x_base_positions[metric_idx] + gender_idx plt.plot([x, x], [row['min'], row['max']], color=gender_colors[row['gender']], linewidth=2) plt.scatter(x, row['avg'], color=gender_colors[row['gender']], s=100, zorder=5, label=row['gender'] if idx in [0, 2] else "") # 配置图表样式 plt.xticks([pos + 0.5 for pos in x_base_positions], x_labels) plt.ylabel('数值') plt.title('不同性别各指标的极值与均值对比') plt.legend(title='性别') plt.grid(axis='y', linestyle='--', alpha=0.7) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者namrorrim
相关产品推荐
相关产品推荐

