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

如何绘制带不同标记的三个中位数连线图并添加误差棒?

解决方法

1. 先计算所需统计量

首先算出每个条件的中位数,以及误差范围(这里用四分位距IQR,更适配中位数;若需要标准差可自行替换):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# 基于你的三个pandas Series计算统计值
stats = pd.DataFrame({
    "中位数": [condition1.median(), condition2.median(), condition3.median()],
    "下四分位": [condition1.quantile(0.25), condition2.quantile(0.25), condition3.quantile(0.25)],
    "上四分位": [condition1.quantile(0.75), condition2.quantile(0.75), condition3.quantile(0.75)]
})
# 计算误差棒的上下差值
stats["误差下限"] = stats["中位数"] - stats["下四分位"]
stats["误差上限"] = stats["上四分位"] - stats["中位数"]

2. 绘制带连线、自定义标记和误差棒的图表

之前的代码问题在于未指定x轴坐标,导致点垂直排列。现在给三个点分配x轴位置,先画连线,再逐个添加不同标记,最后加上误差棒:

# x轴位置和对应标签
x_pos = [0, 1, 2]
cond_labels = ["Condition 1", "Condition 2", "Condition 3"]

# 先画连接三个点的直线
plt.plot(x_pos, stats["中位数"], color="black", linestyle="-", linewidth=2)

# 给每个点添加不同标记
markers = ["o", "*", "D"]
for x, med, marker in zip(x_pos, stats["中位数"], markers):
    plt.scatter(x, med, marker=marker, s=100, zorder=5)  # zorder确保点在连线上方

# 添加误差棒
plt.errorbar(x_pos, stats["中位数"], 
             yerr=[stats["误差下限"], stats["误差上限"]],
             fmt="none", ecolor="black", capsize=5)

# 美化图表
plt.xticks(x_pos, cond_labels)
plt.ylabel("中位数数值")
plt.title("各条件中位数(带四分位距误差棒)")
plt.show()

问题原因说明

  • 你之前单独调用plt.plot(medians[0], marker='o')时,matplotlib默认给单个数值分配x=0,三个点会分别落在(0, med1)、(0, med2)、(0, med3),导致垂直堆叠。
  • plt.plot(medians)会自动分配x为[0,1,2],所以连线正确,但无法给每个点单独设置标记。

可选调整

如果想用标准差代替四分位距作为误差,修改统计量计算即可:

stats["标准差"] = [condition1.std(), condition2.std(), condition3.std()]
# 绘制误差棒时直接传入标准差
plt.errorbar(x_pos, stats["中位数"], yerr=stats["标准差"], fmt="none", ecolor="black", capsize=5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:06:24