简体   繁体   中英

Plotting asymmetric error bars for a single point using errorbar

Goal: To plot asymmetric x error bars for a single point using errorbar. I want to display the inter quartile range (IQR) for a data set.

Code:

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()

Error:

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

My issue is that I am unable to create asymmetric error bars for a single point, where the point will represent the mean and the upper and lower limits of the error bars will be the upper and lower quartile.

I typically use vlines or hlines for this (I think the caps are just distracting):

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

简单的情节

If you still want to use errorbar , you can try

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

带有错误栏

Note that I don't really know how you define your quartiles here, so you may need to make sure you get the right numbers in!!!

Make sure xerr gets a list of lists. If it's only one list, it'll assume it contains symmetrical error bars for two Y's. But there's only one Y, which is why you get the error.

Also your errorbars are wrong. Change the errorbar call to

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

The two arguments you're passing to safezip are of different sizes. The stacktrace you posted says so right here:

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

What that's saying is argument one's length is 1 but argument two's length is 2, so zip can't actually combine those two lists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM