Matplotlib boxplot仅显示最大和最小传单

2024-06-28 19:17:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用plt.boxplot()命令制作标准的Matplotlib-boxplots。 创建boxplot的代码行是:

bp = plt.boxplot(data, whis=[5, 95], showfliers=True)

因为我的数据分布很广,所以我得到的传单很多都超出了规定的范围。为了获得更清晰的出版物质量图,我只想在数据的最大值和最小值处显示单个传单,而不是所有传单。这可能吗?我在文档中看不到任何内置选项来执行此操作。

(我可以将胡须的范围设置为max/min,但这不是我想要的。我想把胡须保持在第5百分位和第95百分位)。

下面是我正在研究的数字。注意传单的密度。 Boxplots


Tags: 代码命令truedata标准matplotlibpltbp
2条回答
fliers = bp['fliers'] 
for i in range(len(fliers)): # iterate through the Line2D objects for the fliers for each boxplot
    box = fliers[i] # this accesses the x and y vectors for the fliers for each box 
    box.set_data([[box.get_xdata()[0],box.get_xdata()[0]],[np.min(box.get_ydata()),‌​np.max(box.get_ydata())]]) 
    # note that you can use any two values from the xdata vector

结果图,仅显示最大和最小传单: enter image description here

plt.boxplot()返回一个字典,其中键fliers包含作为line2d对象的上下传单。您可以在这样绘制之前操纵它们:

仅在matplotlib上>;=1.4.0

bp = plt.boxplot(data, whis=[5, 95], showfliers=True)

# Get a list of Line2D objects, representing a single line from the
# minimum to the maximum flier points.
fliers = bp['fliers']

# Iterate over it!
for fly in fliers:
    fdata = fly.get_data()
    fly.set_data([fdata[0][0],fdata[0][-1]],[fdata[1][0],fdata[1][-1]])

在旧版本上

如果您使用的是旧版本的matplotlib,则每个boxplot的fliers都用两行而不是一行表示。因此,循环看起来像这样:

import numpy as np
for i in range(len(fliers)):
    fdata = fliers[i].get_data()
    # Get the index of the maximum y in data if 
    # i is 0 or even, else get index of minimum y.
    if i%2 == 0:
        id = np.where(fdata[1] == fdata[1].max())[0][0]
    else:
        id = np.where(fdata[1] == fdata[1].min())[0][0]
    fliers[i].set_data([fdata[0][id], fdata[1][id]])

还要注意,showfliers参数在matplotlib<;1.4x中不存在,whisk参数不接受列表。

当然(对于简单的应用程序),您可以在没有传单的情况下绘制boxplot,并将max和min点添加到绘图中:

bp = plt.boxplot(data, whis=[5, 95], showfliers=False)
sc = plt.scatter([1, 1], [data.min(), data.max()])

其中[1, 1]是点的x位置。

相关问题 更多 >