将箱形图的平均值绘制为箱形图

时间:2020-09-03 08:32:22

标签: python numpy matplotlib boxplot

我有一组[6, 17, 5, 1, 4, 7, 14, 19, 0, 10]形式的列表(约100个),我想得到一个箱形图,用于绘制箱形图信息的平均值(即中位数,最大值,最小值,Q1,Q3,所有列表的异常值。

例如,如果我有2个列表

l1 = [6, 17, 5, 1, 4, 7, 14, 19, 0, 10]
l2 = [4, 12, 3, 5, 16, 0, 14, 7, 8, 15]

我可以得到列表的最大值,中值和最小值的平均值,如下所示:

maxs = np.array([])
mins = np.array([])
medians = np.array([])
for l in [l1, l2]:
    medians = np.append(medians, np.median(l))
    maxs = np.append(maxs, np.max(l))
    mins = np.append(mins, np.min(l))
averMax = np.mean(maxs)
averMin = np.mean(mins)
averMedian = np.mean(medians)

对于箱形图中的其他信息,例如平均值Q1,平均值Q3,我应该执行相同的操作。然后,我需要使用此信息(averMax,averMin等)来绘制一个单箱图(而不是一张图中的多个箱图)。

我从Draw Box-Plot with matplotlib获悉,您不必计算普通箱形图的值。您只需要将数据指定为变量。 是否可以针对我的情况执行相同操作,而不是手动计算所有列表的平均值?

1 个答案:

答案 0 :(得分:0)

pd.describe()将获得四分位数,因此您可以基于它们创建图形。我借助this answerofficial reference的示例图来自定义计算得出的数字。

import pandas as pd
import numpy as np
import io

l1 = [6, 17, 5, 1, 4, 7, 14, 19, 0, 10]
l2 = [4, 12, 3, 5, 16, 0, 14, 7, 8, 15]

df = pd.DataFrame({'l1':l1, 'l2':l2}, index=np.arange(len(l1)))

df.describe()
l1  l2
count   10.000000   10.000000
mean    8.300000    8.400000
std 6.532823    5.561774
min 0.000000    0.000000
25% 4.250000    4.250000
50% 6.500000    7.500000
75% 13.000000   13.500000
max 19.000000   16.000000

import matplotlib.pyplot as plt

# spread,center, filer_high, flier_low
x1 = [l1[4]-1.5*(l1[6]-l1[4]), l1[4], l1[5], l1[5]+1.5*(l1[6]-l1[4])]
x2 = [l2[4]-1.5*(l2[6]-l2[4]), l2[4], l2[5], l2[5]+1.5*(l2[6]-l2[4])]

fig = plt.figure(figsize=(8,6))

plt.boxplot([x for x in [x1, x2]], 0, 'rs', 1)
plt.xticks([y+1 for y in range(len([x1, x2]))], ['x1', 'x2'])
plt.xlabel('measurement x')
t = plt.title('Box plot')
plt.show()

enter image description here