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

如何将Bland-Altman图的mean、SD+、SD-文本移至左侧

调整Bland-Altman图中均值、SD标注的位置到左侧

我用statsmodels绘制Bland-Altman图时,默认显示在右侧的"mean""SD+""SD-"标注需要移到左侧,原代码如下:

import pandas as pd

df = pd.DataFrame({'A': [5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9,
                         10, 11, 13, 14, 14, 15, 18, 22, 25],
                   'B': [4, 4, 5, 5, 5, 7, 8, 6, 9, 7, 7, 11,
                         13, 13, 12, 13, 14, 19, 19, 24]})

import statsmodels.api as sm
import matplotlib.pyplot as plt

# 创建Bland-Altman图                  
f, ax = plt.subplots(1, figsize = (8,5))
sm.graphics.mean_diff_plot(df.A, df.B, ax = ax)

# 显示Bland-Altman图
plt.show()

解决方案

statsmodels的mean_diff_plot生成的标注文本默认锚定在x轴右侧,我们可以直接获取这些文本元素,修改位置和对齐方式将其移到左侧。

修改后的完整代码

import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9,
                         10, 11, 13, 14, 14, 15, 18, 22, 25],
                   'B': [4, 4, 5, 5, 5, 7, 8, 6, 9, 7, 7, 11,
                         13, 13, 12, 13, 14, 19, 19, 24]})

f, ax = plt.subplots(1, figsize=(8,5))
# 捕获绘图结果(可选,方便后续扩展操作)
baplot = sm.graphics.mean_diff_plot(df.A, df.B, ax=ax)

# 遍历并调整目标标注的位置
for text in ax.texts:
    label_text = text.get_text()
    if label_text in ['mean', 'SD+', 'SD-']:
        # 将文本锚定到x轴最左端,设置左对齐
        text.set_x(ax.get_xlim()[0])
        text.set_ha('left')

plt.show()

代码说明

  1. 遍历坐标轴上的所有文本元素,筛选出需要调整的标注
  2. 通过set_x()将文本位置设为x轴的最小值(最左端)
  3. 用set_ha('left')设置左对齐,确保文本紧贴左侧显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:40:25