通过参考此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.8
和21.2
的箱图中绘制两个异常值的数据点。
我认为该错误在此附近:
...
for v in outliers:
fliers[0].set(xdata = 1, ydata = v)
...
我了解到,因为我只有一个箱形图,所以可以像fliers[0]
这样进行下标,以从箱形图中获取第一个箱形图。 xdata = 1
,因为我再次在第一个方框中设置了该值,然后在ydata=v
中设置了离群值的y值。
我的代码中的错误在哪里?
答案 0 :(得分:1)
让我们尝试一下:
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])
输出: