You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中绘制分组数据中位数并反转直方图顺序

分组直方图优化:添加中位数线+调整分组顺序

先看原代码,它能生成A、B两组数据的直方图:

from pandas import DataFrame
import numpy as np
x = ['A']*300 + ['B']*400 
y = np.random.randn(700)
df = DataFrame({'Letter': x, 'N': y})
df.hist('N', by='Letter')

要实现两个需求,直接看修改后的代码:

from pandas import DataFrame
import numpy as np
import matplotlib.pyplot as plt

# 生成原始数据
x = ['A']*300 + ['B']*400 
y = np.random.randn(700)
df = DataFrame({'Letter': x, 'N': y})

# 1. 调整分组顺序:把B设为第一个分组,A在后
df['Letter'] = df['Letter'].astype('category').cat.set_categories(['B', 'A'], ordered=True)

# 绘制分组直方图,获取子图对象
axs = df.hist('N', by='Letter', figsize=(10, 5))

# 2. 计算每组的中位数,添加垂直线
medians = df.groupby('Letter')['N'].median()
# 遍历每个子图,对应分组画中位数线
for ax, (letter, median) in zip(axs.flat, medians.items()):
    ax.axvline(median, color='red', linestyle='--', linewidth=2)
    # 给中位数线加标注,方便查看数值
    ax.text(median, ax.get_ylim()[1]*0.9, f'Median: {median:.2f}', 
            color='red', ha='center')

plt.tight_layout()
plt.show()

关键部分说明:

  • 调整分组顺序:把Letter列转为有序分类,指定['B','A']的顺序,这样hist的by参数就会按这个顺序生成子图,B组自然在左侧。
  • 添加中位数线:先用groupby计算每组中位数,再遍历每个子图,用axvline画红色虚线作为中位数标记,同时添加文本标注显示具体数值,更直观。

内容的提问来源于stack exchange,提问作者Ale Rey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:42:47