Note

Go to the endto download the full example code.

Create boxes from error bars using PatchCollection#

In this example, we snazz up a pretty standard error bar plot by addinga rectangle patch defined by the limits of the bars in both the x- andy- directions. To do this, we have to write our own custom functioncalledmake_error_boxes. Close inspection of this function willreveal the preferred pattern in writing functions for matplotlib:

  1. anAxes object is passed directly to the function

  2. the function operates on theAxes methods directly, not throughthepyplot interface

  3. plotting keyword arguments that could be abbreviated are spelled out forbetter code readability in the future (for example we usefacecolorinstead offc)

  4. the artists returned by theAxes plotting methods are thenreturned by the function so that, if desired, their stylescan be modified later outside of the function (they are notmodified in this example).

importmatplotlib.pyplotaspltimportnumpyasnpfrommatplotlib.collectionsimportPatchCollectionfrommatplotlib.patchesimportRectangle# Number of data pointsn=5# Dummy datanp.random.seed(19680801)x=np.arange(0,n,1)y=np.random.rand(n)*5.# Dummy errors (above and below)xerr=np.random.rand(2,n)+0.1yerr=np.random.rand(2,n)+0.2defmake_error_boxes(ax,xdata,ydata,xerror,yerror,facecolor='r',edgecolor='none',alpha=0.5):# Loop over data points; create box from errors at each pointerrorboxes=[Rectangle((x-xe[0],y-ye[0]),xe.sum(),ye.sum())forx,y,xe,yeinzip(xdata,ydata,xerror.T,yerror.T)]# Create patch collection with specified colour/alphapc=PatchCollection(errorboxes,facecolor=facecolor,alpha=alpha,edgecolor=edgecolor)# Add collection to Axesax.add_collection(pc)# Plot errorbarsartists=ax.errorbar(xdata,ydata,xerr=xerror,yerr=yerror,fmt='none',ecolor='k')returnartists# Create figure and Axesfig,ax=plt.subplots(1)# Call function to create error boxes_=make_error_boxes(ax,x,y,xerr,yerr)plt.show()
errorbars and boxes

Tags:plot-type: errorbarcomponent: rectanglecomponent: patchcollectiondomain: statistics

References

The use of the following functions, methods, classes and modules is shownin this example:

Gallery generated by Sphinx-Gallery