如何绘制带均值与单个值的嵌套分类图(非箱线/柱状图)
实现嵌套X轴的均值+单值分类图
直接手动构建双层X轴就能复刻Minitab的效果,不用拆分图表,以下是具体实现:
步骤1:数据预处理
先分组计算均值,同时给每个Product-Tester组合分配X轴位置,避免重叠:
import pandas as pd import matplotlib.pyplot as plt import numpy as np # 假设你的数据集是df # 计算每个Product-Tester组合的均值 mean_results = df.groupby(['Product', 'Tester'])['Result'].mean().reset_index() # 定义分类顺序,避免自动排序混乱 unique_products = df['Product'].unique() unique_testers = df['Tester'].unique() # 给每个组合分配X坐标:大组(Product)之间留空,避免挤在一起 group_gap = len(unique_testers) + 2 x_positions = {} for prod_idx, product in enumerate(unique_products): base = prod_idx * group_gap for test_idx, tester in enumerate(unique_testers): x_positions[(product, tester)] = base + test_idx
步骤2:绘制单个数据点
用散点图把所有原始测试结果画上去:
fig, ax = plt.subplots(figsize=(10, 6)) # 画单个数据点,灰色半透明区分均值 for (prod, test), subset in df.groupby(['Product', 'Tester']): x = x_positions[(prod, test)] ax.scatter([x]*len(subset), subset['Result'], color='#888888', alpha=0.6, zorder=1)
步骤3:绘制均值标记
用醒目的样式突出每个组合的均值:
# 画均值点,红色实心点带黑边,层级高于原始数据 for _, row in mean_results.iterrows(): x = x_positions[(row['Product'], row['Tester'])] ax.scatter(x, row['Result'], color='red', s=80, zorder=2, edgecolor='black')
步骤4:搭建双层X轴
手动设置两层X轴的标签和位置,对齐大组中心:
# 底层X轴:显示Tester ax.set_xticks([pos for (prod, test), pos in x_positions.items()]) ax.set_xticklabels([test for (prod, test), pos in x_positions.items()]) # 上层X轴:显示Product,位置对齐每个Product组的中心 top_ax = ax.twiny() prod_centers = [idx*group_gap + (len(unique_testers)-1)/2 for idx in range(len(unique_products))] top_ax.set_xticks(prod_centers) top_ax.set_xticklabels(unique_products) top_ax.tick_params(axis='x', pad=15) # 拉开间距避免和底层标签重叠 # 可选:添加组分隔线,更清晰区分不同Product for idx in range(1, len(unique_products)): ax.axvline(x=idx*group_gap - 1, color='#dddddd', linestyle='--') # 完善图表标签 ax.set_xlabel('Tester') top_ax.set_xlabel('Product') ax.set_ylabel('Result') plt.title('Nested X-axis Plot with Individual Results and Means') plt.tight_layout() plt.show()
额外调整建议
- 如果需要给均值添加连线,把
scatter换成plot即可 - 可以根据数据量调整
group_gap的大小,避免标签拥挤 - 数据点和均值的样式、颜色都可以自定义,匹配你的需求
内容的提问来源于stack exchange,提问作者Steve..Johnson
相关产品推荐
相关产品推荐

