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

如何将matplotlib的LineCollection对象转字符串并提取小提琴图cmeans值

提取matplotlib小提琴图LineCollection对象存储的数值

matplotlib的LineCollection对象存储的所有线段坐标可以通过自带的get_segments()方法直接获取。小提琴图返回的cmeans对应的是每个分布均值位置的水平短横线,每个线段两个端点的x坐标中点就是对应的均值数值。

具体提取代码

import matplotlib.pyplot as plt
import numpy as np

# 示例:生成测试数据绘制小提琴图
data = [np.random.normal(0, 1, 100), np.random.normal(2, 1.5, 100), np.random.normal(-1, 0.8, 100)]
violin_dict = plt.violinplot(data, showmeans=True)

# 提取cmeans的LineCollection对象
cmeans_lc = violin_dict['cmeans']

# 获取所有线段数据,每个线段对应一个小提琴的均值线
segments = cmeans_lc.get_segments()

# 提取所有均值数值
mean_list = []
for seg in segments:
    # 每个线段结构为[[x1, y], [x2, y]],x坐标的平均值即为对应均值
    mean_val = seg[:, 0].mean()
    mean_list.append(mean_val)

# 输出结果
print(mean_list)

通用适配说明

该提取逻辑同样适用于小提琴图返回字典中其他同类LineCollection对象:

  • cmedians:中位数线段,提取方法和均值完全一致
  • cmins:最小值线段
  • cmaxes:最大值线段
  • cbars:箱线范围线段,取x坐标中点即可得到对应分位数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 00:54:01