使用errorbar绘制单个点的非对称误差线

11

目标:使用errorbar绘制单个点的非对称x误差线。我想显示数据集的四分位距(IQR)。

代码:

import numpy as np
import matplotlib.pyplot as plt

y = 1.0
data = np.random.rand(100)

median = np.median(data)
upper_quartile = np.percentile(data, 75)
lower_quartile = np.percentile(data, 25)
IQR = upper_quartile - lower_quartile

plt.errorbar(median, y, xerr=[lower_quartile ,upper_quartile], fmt='k--')

plt.savefig('IQR.eps')
plt.show()

错误:

Traceback (most recent call last):
  File "IQR.py", line 15, in <module>
    plt.errorbar(median, y, xerr=[0.5,0.75], fmt='k--')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2251, in errorbar
    ret = ax.errorbar(x, y, yerr, xerr, fmt, ecolor, elinewidth, capsize, barsabove, lolims, uplims, xlolims, xuplims, **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 5327, in errorbar
    in cbook.safezip(x,xerr)]
  File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 1294, in safezip
    raise ValueError(_safezip_msg % (Nx, i+1, len(arg)))
ValueError: In safezip, len(args[0])=1 but len(args[1])=2

我的问题是我无法为单个点创建不对称的误差线,其中该点将代表均值,误差线的上限和下限将分别为上四分位数和下四分位数。


3个回答

17

对于这个问题,我通常使用vlines或者hlines(我认为大写字母只会分散注意力):

 plt.hlines( y, median-lower_quartile, median+upper_quartile)
 plt.plot(median, y, 'o')

简单的图表

如果你仍然想使用errorbar,你可以尝试以下方法:

plt.errorbar(median, y, xerr=np.array([[lower_quartile ,upper_quartile]]).T, 
        fmt='ko')

带有误差线的图表

请注意,我不确定您在这里如何定义四分位数,因此您可能需要确保获得正确的数字!!!


1
谢谢@Jose!这正是我在寻找的。 - De_n00bWOLF
1
还要特别感谢@Jose:我曾经为了将一个错误图映射到Seaborn FacetGrid并传入一个2xN矩阵而苦苦挣扎。现在好多了。 - jonsedar

2

确保xerr得到的是一个列表的列表。如果只有一个列表,它将假定该列表包含两个Y轴的对称误差条。但只有一个Y轴,这就是为什么会出现错误的原因。

此外,您的误差条是错误的。将errorbar调用更改为

plt.errorbar(median, y, xerr=[[median-lower_quartile ,upper_quartile-median]], fmt='k--')


-1

你传递给 safezip 的两个参数大小不同。你发布的堆栈跟踪就在这里说了:

ValueError: In safezip, len(args[0])=1 but len(args[1])=2

这句话的意思是第一个参数的长度为1,但第二个参数的长度为2,因此zip无法将这两个列表组合在一起。


谢谢。有没有关于如何为单个点绘制不对称误差线的建议? - De_n00bWOLF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接