使用带有异常值的 Matplotlib 手动绘制箱线图

Manually Drawing Box Plot Using Matplotlib with Outliers

参考这个Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?,我想画一个箱线图给定五数摘要和离群值。

问题给出的答案是针对多个箱线图的,我修改了代码以适合单个箱线图。

这是我试过的代码:

def custom_boxplot(mini, q1, q2, q3, maxm, *outliers):
    """
    Input: 
        Five-number summary separated into different arguments;
        The following arguments after the summary are the outliers.
    Output:
        A boxplot drawn in the console.
    """
    figure = plt.figure(figsize=(8,8))
    ax = plt.gca()
    bp = plt.boxplot([mini, q1, q2, q3, maxm])
    fliers = bp['fliers']
    for v in outliers:
        fliers[0].set(xdata = 1, ydata = v)
    _all = [mini, q1, q2, q3, maxm] + list(outliers)
    _min, _max = min(_all), max(_all)
    ax.set_ylim([_min*0.9, _max*1.1])

    figure.canvas.draw()

但是,当我尝试 运行 使用以下行时

custom_boxplot(43.2, 43.5, 51.05, 56.8, 69.3, 13.8, 21.2)

它输出的箱线图只有一个来自最后一个参数的离群值。我预计在 13.821.2 的箱线图中绘制了两个异常值数据点。

我认为错误出在附近:

...
    for v in outliers:
        fliers[0].set(xdata = 1, ydata = v)
...

我知道因为我只有一个箱线图,所以我可以像 fliers[0] 那样进行下标以从箱线图中获取第一个箱子。 xdata = 1 因为我再次为第一个框设置它,然后 ydata=v 用于设置离群值的 y 值。 我的代码哪里出错了?

让我们试试这个:

def custom_boxplot(mini, q1, q2, q3, maxm, *outliers):
    """
    Input: 
        Five-number summary separated into different arguments;
        The following arguments after the summary are the outliers.
    Output:
        A boxplot drawn in the console.
    """
    figure = plt.figure(figsize=(8,8))
    ax = plt.gca()
    bp = plt.boxplot([mini, q1, q2, q3, maxm])
    fliers = bp['fliers']
    fliers[0].set(xdata = [1]*len(outliers), ydata = outliers)
    _all = [mini, q1, q2, q3, maxm] + list(outliers)
    _min, _max = min(_all), max(_all)
    ax.set_ylim([_min*0.9, _max*1.1])

输出: