【问题标题】:Getting data of a box plot - Matplotlib获取箱线图的数据 - Matplotlib
【发布时间】:2018-06-26 05:22:24
【问题描述】:

我必须绘制一些数据的箱线图,这可以通过 Matplotlib 轻松完成。但是,我被要求提供一个表格,其中包含那里提供的数据,例如胡须、中位数、标准差等。

我知道我可以“手动”计算这些,但从参考资料中我也知道boxplot 方法:

Returns a dictionary mapping each component of the boxplot to a list of the matplotlib.lines.Line2D instances created. That dictionary has the following keys (assuming vertical boxplots):

boxes: the main body of the boxplot showing the quartiles and the median’s confidence intervals if enabled.
medians: horizonal lines at the median of each box.
whiskers: the vertical lines extending to the most extreme, n-outlier data points.
caps: the horizontal lines at the ends of the whiskers.
fliers: points representing data that extend beyone the whiskers (outliers).

所以我想知道如何获得这些值,因为它们是 ma​​tplotlib.lines.Line2D

谢谢。

【问题讨论】:

  • “手工”计算这些有什么问题?大多数信息都可以通过numpy 轻松获得,例如与np.median,或np.minnp.max
  • @BenjaminBannier:特别是对于大型数据集,这是重复工作,因为在创建箱线图时已经调用了更昂贵的函数,例如 median
  • 没错,@jmetz!这些原因我想知道如何从已经计算的箱形图中获取这些值。
  • @pceccon,是的,这是有道理的。

标签: python matplotlib boxplot


【解决方案1】:

如您所见,您需要访问 boxplot 的返回值的成员。

即,例如如果你的返回值存储在bp

bp['medians'][0].get_ydata()

>> array([ 2.5,  2.5])

由于箱线图是垂直的,而中线因此是水平线,您只需要关注其中一个y值即可;即我的样本数据的中位数为 2.5。

对于字典中的每个“键”,值将是一个用于处理多个框的列表。如果您只有一个箱线图,则列表将只有一个元素,因此我在上面使用了bp['medians'][0]。 如果您的箱线图中有多个框,则需要使用例如迭代它们。

for medline in bp['medians']:
    linedata = medline.get_ydata()
    median = linedata[0]

不幸的是,CT Zhu 的回答不起作用,因为不同的元素表现不同。还有例如只有一个中位数,但有两个胡须……因此,按照上面概述的方式手动处理每个数量是最安全的。

注意你能来的最接近的是以下;

res  = {}
for key, value in bp.items():
    res[key] = [v.get_data() for v in value]

或等价的

res = {key : [v.get_data() for v in value] for key, value in bp.items()}

【讨论】:

  • 谢谢!在bp['medians'][0] 中,为什么是 [0]?如果我只有一个箱形图,这与bp['medians'] 不一样?为什么这会返回一个包含两个值的数组?我问这个是因为我想知道我是否必须查看第一个或第二个,或者它们是否相同,这似乎没有意义。
  • 是的,你是对的,结果 CT Zhu 的答案根本不起作用:/ 认为你必须分别对待每个项目(中位数、大写字母、盒子等)
  • @pceccon:我错误地认为 CT Zhu 的回答有效;它没有。我已经相应地更新了我的答案。
  • 感谢您的宝贵时间,@jmetz。
  • 一个盒子有 4 条边,在绘图时有 5 个节点。 (起始节点在末尾重复)。
猜你喜欢
  • 2016-02-04
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2016-06-22
  • 2010-12-03
  • 2018-07-12
  • 2013-05-11
  • 2021-06-26
相关资源
最近更新 更多