pce*_*con 4 python matplotlib boxplot
我必须绘制一些数据的箱线图,我可以使用Matplotlib轻松完成。但是,我被要求提供一个表格,其中包含其中显示的数据,例如须线、中位数、标准差等。
\n\n我知道我可以“手动”计算这些,但我也从参考文献中知道该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):\n\nboxes: the main body of the boxplot showing the quartiles and the median\xe2\x80\x99s confidence intervals if enabled.\nmedians: horizonal lines at the median of each box.\nwhiskers: the vertical lines extending to the most extreme, n-outlier data points.\ncaps: the horizontal lines at the ends of the whiskers.\nfliers: points representing data that extend beyone the whiskers (outliers).\n
Run Code Online (Sandbox Code Playgroud)\n\n所以我想知道如何获得这些值,因为它们是matplotlib.lines.Line2D。
\n\n谢谢。
\n正如您所了解的,您需要访问箱线图的返回值的成员。
也就是说,例如,如果您的返回值存储在bp
bp['medians'][0].get_ydata()
>> array([ 2.5, 2.5])
Run Code Online (Sandbox Code Playgroud)
由于箱线图是垂直的,因此中线是水平线,因此您只需关注其中一个 y 值;即我的样本数据的中位数是 2.5。
对于字典中的每个“键”,其值将是一个用于处理多个框的列表。如果您只有一个箱线图,则该列表将只有一个元素,因此我在上面使用了bp['medians']
[0]。如果箱线图中有多个框,则需要使用例如迭代它们
for medline in bp['medians']:
linedata = medline.get_ydata()
median = linedata[0]
Run Code Online (Sandbox Code Playgroud)
不幸的是,CT Zhu 的答案不起作用,因为不同的元素表现不同。另外,例如,只有一个中位数,但有两个晶须……因此,按照上述方式手动处理每个数量是最安全的。
注意,您可以得到的最接近的是以下内容;
res = {}
for key, value in bp.items():
res[key] = [v.get_data() for v in value]
Run Code Online (Sandbox Code Playgroud)
或同等地
res = {key : [v.get_data() for v in value] for key, value in bp.items()}
Run Code Online (Sandbox Code Playgroud)