使用预计算(汇总)统计数据绘制箱线图
我想在Python和matplotlib中做一个箱线图,但我没有原始的“原始”数据。现在我手里有一些预先计算好的值,比如最大值、最小值、平均值、中位数和四分位距(假设数据是正态分布的),但我还是想做一个箱线图。当然,画出异常值是不可能的,但我觉得其他信息应该都在。
我到处找答案,但都没有成功。我找到的最接近的一个问题是关于R语言的(我对这个不太熟悉)。可以查看这个链接:是否可以轻松地从之前计算的统计数据绘制箱线图(在R中?)
3 个回答
9
提到@MKroehnert的回答和在 https://matplotlib.org/gallery/statistics/bxp.html 上的 Boxplot drawer function
,以下内容可能会对你有帮助:
import matplotlib.pyplot as plt
stats = [{
"label": 'A', # not required
"mean": 5, # not required
"med": 5.5,
"q1": 3.5,
"q3": 7.5,
# "cilo": 5.3 # not required
# "cihi": 5.7 # not required
"whislo": 2.0, # required
"whishi": 8.0, # required
"fliers": [] # required if showfliers=True
}]
fs = 10 # fontsize
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.set_title('Boxplot for precalculated statistics', fontsize=fs)
plt.show()
21
感谢@tacaswell的评论,我找到了需要的文档,并用Matplotlib 1.4.3做了一个示例。不过,这个示例并不能自动调整图形到合适的大小。
import matplotlib.pyplot as plt
item = {}
item["label"] = 'box' # not required
item["mean"] = 5 # not required
item["med"] = 5.5
item["q1"] = 3.5
item["q3"] = 7.5
#item["cilo"] = 5.3 # not required
#item["cihi"] = 5.7 # not required
item["whislo"] = 2.0 # required
item["whishi"] = 8.0 # required
item["fliers"] = [] # required if showfliers=True
stats = [item]
fig, axes = plt.subplots(1, 1)
axes.bxp(stats)
axes.set_title('Default')
y_axis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y_values = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
plt.yticks(y_axis, y_values)
以下是相关文档的链接:
9
在旧版本中,你需要手动一个一个地修改箱线图的元素:
Mean=[3.4] #mean
IQR=[3.0,3.9] #inter quantile range
CL=[2.0,5.0] #confidence limit
A=np.random.random(50)
D=plt.boxplot(A) # a simple case with just one variable to boxplot
D['medians'][0].set_ydata(Mean)
D['boxes'][0]._xy[[0,1,4], 1]=IQR[0]
D['boxes'][0]._xy[[2,3],1]=IQR[1]
D['whiskers'][0].set_ydata(np.array([IQR[0], CL[0]]))
D['whiskers'][1].set_ydata(np.array([IQR[1], CL[1]]))
D['caps'][0].set_ydata(np.array([CL[0], CL[0]]))
D['caps'][1].set_ydata(np.array([CL[1], CL[1]]))
_=plt.ylim(np.array(CL)+[-0.1*np.ptp(CL), 0.1*np.ptp(CL)]) #reset the limit