Plt bar error

Plot y versus x as lines and/or markers with attached errorbars.
matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=», ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)[source]#

Plot y versus x as lines and/or markers with attached errorbars.

x, y define the data locations, xerr, yerr define the errorbar
sizes. By default, this draws the data markers/lines as well the
errorbars. Use fmt=’none’ to draw errorbars without any data markers.

Parameters:
x, yfloat or array-like

The data positions.

xerr, yerrfloat or array-like, shape(N,) or shape(2, N), optional

The errorbar sizes:

  • scalar: Symmetric +/- values for all data points.

  • shape(N,): Symmetric +/-values for each data point.

  • shape(2, N): Separate — and + values for each bar. First row
    contains the lower errors, the second row contains the upper
    errors.

  • None: No errorbar.

All values must be >= 0.

See Different ways of specifying error bars
for an example on the usage of xerr and yerr.

fmtstr, default: »

The format for the data points / data lines. See plot for
details.

Use ‘none’ (case insensitive) to plot errorbars without any data
markers.

ecolorcolor, default: None

The color of the errorbar lines. If None, use the color of the
line connecting the markers.

elinewidthfloat, default: None

The linewidth of the errorbar lines. If None, the linewidth of
the current style is used.

capsizefloat, default: rcParams["errorbar.capsize"] (default: 0.0)

The length of the error bar caps in points.

capthickfloat, default: None

An alias to the keyword argument markeredgewidth (a.k.a. mew).
This setting is a more sensible name for the property that
controls the thickness of the error bar cap in points. For
backwards compatibility, if mew or markeredgewidth are given,
then they will over-ride capthick. This may change in future
releases.

barsabovebool, default: False

If True, will plot the errorbars above the plot
symbols. Default is below.

lolims, uplims, xlolims, xuplimsbool, default: False

These arguments can be used to indicate that a value gives only
upper/lower limits. In that case a caret symbol is used to
indicate this. lims-arguments may be scalars, or array-likes of
the same length as xerr and yerr. To use limits with inverted
axes, set_xlim or set_ylim must be called before
errorbar(). Note the tricky parameter names: setting e.g.
lolims to True means that the y-value is a lower limit of the
True value, so, only an upward-pointing arrow will be drawn!

erroreveryint or (int, int), default: 1

draws error bars on a subset of the data. errorevery =N draws
error bars on the points (x[::N], y[::N]).
errorevery =(start, N) draws error bars on the points
(x[start::N], y[start::N]). e.g. errorevery=(6, 3)
adds error bars to the data at (x[6], x[9], x[12], x[15], …).
Used to avoid overlapping error bars when two series share x-axis
values.

Returns:
ErrorbarContainer

The container contains:

  • plotline: Line2D instance of x, y plot markers and/or line.

  • caplines: A tuple of Line2D instances of the error bar caps.

  • barlinecols: A tuple of LineCollection with the horizontal and
    vertical error ranges.

Other Parameters:
dataindexable object, optional

If given, the following parameters also accept a string s, which is
interpreted as data[s] (unless this raises an exception):

x, y, xerr, yerr

**kwargs

All other keyword arguments are passed on to the plot call
drawing the markers. For example, this code makes big red squares
with thick green edges:

x, y, yerr = rand(3, 10)
errorbar(x, y, yerr, marker='s', mfc='red',
         mec='green', ms=20, mew=4)

where mfc, mec, ms and mew are aliases for the longer
property names, markerfacecolor, markeredgecolor, markersize
and markeredgewidth.

Valid kwargs for the marker properties are:

  • dashes

  • dash_capstyle

  • dash_joinstyle

  • drawstyle

  • fillstyle

  • linestyle

  • marker

  • markeredgecolor

  • markeredgewidth

  • markerfacecolor

  • markerfacecoloralt

  • markersize

  • markevery

  • solid_capstyle

  • solid_joinstyle

Refer to the corresponding Line2D property for more details:

Property

Description

agg_filter

a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image

alpha

scalar or None

animated

bool

antialiased or aa

bool

clip_box

Bbox

clip_on

bool

clip_path

Patch or (Path, Transform) or None

color or c

color

dash_capstyle

CapStyle or {‘butt’, ‘projecting’, ’round’}

dash_joinstyle

JoinStyle or {‘miter’, ’round’, ‘bevel’}

dashes

sequence of floats (on/off ink in points) or (None, None)

data

(2, N) array or two 1D arrays

drawstyle or ds

{‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’

figure

Figure

fillstyle

{‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}

gapcolor

color or None

gid

str

in_layout

bool

label

object

linestyle or ls

{‘-‘, ‘—‘, ‘-.’, ‘:’, », (offset, on-off-seq), …}

linewidth or lw

float

marker

marker style string, Path or MarkerStyle

markeredgecolor or mec

color

markeredgewidth or mew

float

markerfacecolor or mfc

color

markerfacecoloralt or mfcalt

color

markersize or ms

float

markevery

None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]

mouseover

bool

path_effects

AbstractPathEffect

picker

float or callable[[Artist, Event], tuple[bool, dict]]

pickradius

unknown

rasterized

bool

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

solid_capstyle

CapStyle or {‘butt’, ‘projecting’, ’round’}

solid_joinstyle

JoinStyle or {‘miter’, ’round’, ‘bevel’}

transform

unknown

url

str

visible

bool

xdata

1D array

ydata

1D array

zorder

float

Examples using matplotlib.pyplot.errorbar#

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Prerequisites: Matplotlib

    In this article, we will create a bar plot with error bars using Matplotlib. Error bar charts are a great way to represent the variability in your data. It can be applied to graphs to provide an additional layer of detailed information on the presented data. 

    Approach:

    • Import required python library.
    • Making simple data.
    • Plot using plt.errorbar() function
    • Display graph

    The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines and/or markers with attached errorbars.

    Syntax: matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)

    Parameters: This method accept the following parameters that are described below:

    • x, y: These parameters are the horizontal and vertical coordinates of the data points.
    • ecolor: This parameter is an optional parameter. And it is the color of the errorbar lines with default value NONE.
    • elinewidth: This parameter is also an optional parameter. And it is the linewidth of the errorbar lines with default value NONE.
    • capsize: This parameter is also an optional parameter. And it is the length of the error bar caps in points with default value NONE.
    • barsabove: This parameter is also an optional parameter. It contains boolean value True for plotting errorsbars above the plot symbols.Its default value is False.

    Implementation using the approach above is given below:

    Example 1:  Adding Some errors in a ‘y’ value.

    Python3

    import matplotlib.pyplot as plt

    a = [1, 3, 5, 7]

    b = [11, 2, 4, 19]

    plt.bar(a, b)

    c = [1, 3, 2, 1]

    plt.errorbar(a, b, yerr=c, fmt="o", color="r")

    plt.show()

    Output:

    Example 2:  Adding Some errors in the ‘x’ value.

    Python3

    import matplotlib.pyplot as plt

    a = [1, 3, 5, 7]

    b = [11, 2, 4, 19]

    plt.bar(a, b)

    c = [1, 3, 2, 1]

    plt.errorbar(a, b, xerr=c, fmt="o", color="r")

    plt.show()

    Output:

    Example 3: Adding error in x and y

    Python3

    import matplotlib.pyplot as plt

    a = [1, 3, 5, 7]

    b = [11, 2, 4, 19]

    plt.bar(a, b)

    c = [1, 3, 2, 1]

    d = [1, 3, 2, 1]

    plt.errorbar(a, b, xerr=c, yerr=d, fmt="o", color="r")

    plt.show()

    Output:

    Example 4: Adding variable error in x and y.

    Python3

    import matplotlib.pyplot as plt

    x = [1, 2, 3, 4, 5]

    y = [1, 2, 1, 2, 1]

    y_errormin = [0.1, 0.5, 0.9, 0.1, 0.9]

    y_errormax = [0.2, 0.4, 0.60.4, 0.2]

    x_error = 0.5

    y_error = [y_errormin, y_errormax]

    plt.bar(x, y)

    plt.errorbar(x, y,

                 yerr=y_error,

                 xerr=x_error,

                 fmt='o', color="r"

    plt.show()

    Output:

    For any scientific measurement, accurate accounting for errors is nearly as important, if not more important, than accurate reporting of the number itself.
    For example, imagine that I am using some astrophysical observations to estimate the Hubble Constant, the local measurement of the expansion rate of the Universe.
    I know that the current literature suggests a value of around 71 (km/s)/Mpc, and I measure a value of 74 (km/s)/Mpc with my method. Are the values consistent? The only correct answer, given this information, is this: there is no way to know.

    Suppose I augment this information with reported uncertainties: the current literature suggests a value of around 71 $pm$ 2.5 (km/s)/Mpc, and my method has measured a value of 74 $pm$ 5 (km/s)/Mpc. Now are the values consistent? That is a question that can be quantitatively answered.

    In visualization of data and results, showing these errors effectively can make a plot convey much more complete information.

    Basic Errorbars¶

    A basic errorbar can be created with a single Matplotlib function call:

    Here the fmt is a format code controlling the appearance of lines and points, and has the same syntax as the shorthand used in plt.plot, outlined in Simple Line Plots and Simple Scatter Plots.

    In addition to these basic options, the errorbar function has many options to fine-tune the outputs.
    Using these additional options you can easily customize the aesthetics of your errorbar plot.
    I often find it helpful, especially in crowded plots, to make the errorbars lighter than the points themselves:

    In addition to these options, you can also specify horizontal errorbars (xerr), one-sided errorbars, and many other variants.
    For more information on the options available, refer to the docstring of plt.errorbar.

    Continuous Errors¶

    In some situations it is desirable to show errorbars on continuous quantities.
    Though Matplotlib does not have a built-in convenience routine for this type of application, it’s relatively easy to combine primitives like plt.plot and plt.fill_between for a useful result.

    Here we’ll perform a simple Gaussian process regression, using the Scikit-Learn API (see Introducing Scikit-Learn for details).
    This is a method of fitting a very flexible non-parametric function to data with a continuous measure of the uncertainty.
    We won’t delve into the details of Gaussian process regression at this point, but will focus instead on how you might visualize such a continuous error measurement:

    We now have xfit, yfit, and dyfit, which sample the continuous fit to our data.
    We could pass these to the plt.errorbar function as above, but we don’t really want to plot 1,000 points with 1,000 errorbars.
    Instead, we can use the plt.fill_between function with a light color to visualize this continuous error:

    Note what we’ve done here with the fill_between function: we pass an x value, then the lower y-bound, then the upper y-bound, and the result is that the area between these regions is filled.

    The resulting figure gives a very intuitive view into what the Gaussian process regression algorithm is doing: in regions near a measured data point, the model is strongly constrained and this is reflected in the small model errors.
    In regions far from a measured data point, the model is not strongly constrained, and the model errors increase.

    For more information on the options available in plt.fill_between() (and the closely related plt.fill() function), see the function docstring or the Matplotlib documentation.

    Finally, if this seems a bit too low level for your taste, refer to Visualization With Seaborn, where we discuss the Seaborn package, which has a more streamlined API for visualizing this type of continuous errorbar.

    Overview

    Error is a deviation from the calculated value and actual value. When we graphically represent the data, some of it has irregularities. To mark these uncertainties and ambiguity, we use Error bars. They are used to show the errors in the plots. Matplotlib provides a function that can plot error bars along with the data to find ambiguity and improve the data’s accuracy. We are going to discuss about how we can plot error bars in matplotlib with some examples.

    Scope

    For plotting error bars in matplotlib, First, we have to import the required library (Matplotlib), from which we can use the function of error bars to plot it along with the data. We will also discuss the syntax, parameter, and return value of error bars in matplotlib to better understand the topic. Examples of implementing error bars in matplotlib are given below.

    • Simplest errorbar
    • Error bar with the only x-error axis
    • Error bar with the only y-error axis
    • Interactive Error bar in matplotlib
    • Scatter plot with error bars
    • Error bar in the bar graph

    What are Error Bars in matplotlib?

    Error bars in matplotlib are y vs. x as planes generated at each coordinate plotted on the axes. These are used to show the standard deviation or ambiguity to better understand the data’s accuracy. They can be implemented on different plots like line plots, scatter plots, and bar graphs.

    So what is the Function used for Matplotlib Errorbars?

    We have: matplotlib.pyplot.errorbar()for this! It takes atleast 2 parameters to plot error bars along with the data.

    Two more optional parameters are actually behind the plotting of the error bar xerr and yerr. These parameters plot the error bar at each coordinate representing the data.

    A Simple example of error bars in matplotlib.

    error bars in matplotlib

    Syntax of Matplotlib Errorbar

    matplotlib.pyplot.errorbar(x, y, yerr=None,
    xerr=None, fmt='', ecolor=None, elinewidth=None, 
    capsize=None, barsabove=False, lolims=False,
    uplims=False, xlolims=False, xuplims=False,
    errorevery=1, capthick=None, *, data=None, **kwargs)
    

    Parameters of Matplotlib errorbar

    • x, y: Array or list of x and y axes data points to plot coordinates on the graph.
    • xerr, yerr: An array or list of positive values.
    • fmt (optional parameter): The data points/lines format contains the string value.
    • ecolor (optional parameter): Color of the errorbar lines.
    • elinewidth (optional parameter): Linewidth of the errorbar lines
    • capsize (optional parameter): The length of the error bar caps in points and default 0.0.
    • barsabove (optional parameter): The datatype of this parameter is bool, and the default value is false. If true, will plot the error bars above the plot symbols.
    • lolims, uplims, xlolims, xuplims (optional parameters): The data type of this parameter is bool, and the default value is false. They contain boolean values, indicating that a value only gives upper/lower limits.
    • capthick (optional parameter): The datatype of this parameter is float and the default value is none. It controls the thickness of the error bar cap in points.
    • errorevery (optional parameter): The datatype of this parameter is int, and the default value is 1. It contains integer values used to draw error bars on a subset of the data.

    The Return Value of Matplotlib Errorbar

    Matplotlib errorbar returns the ErrorbarContainer

    The container contains:

    • plotline: Line2D instance of x, y plot markers and line.
    • caplines: A tuple of Line2D instances of the error bar caps.
    • barlinecols: A tuple of collections of lines along with Horizontal and vertical error ranges.

    Examples of Matplotlib Errorbar

    Example1: Simplest Errorbar

    # This code is written in python
    # Importing the required module
    import matplotlib.pyplot as plt
    
    # x and y data points
    x=[1,2,3,4,5,6]
    y=[1,9,2,8,3,7]
    
    
    plt.title("Simplest errorbars")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    
    # function to plot errorbar with the line plots
    plt.errorbar(x,y,xerr=0.5,yerr=1)
    plt.grid()
    plt.show()
    

    Output:

    Simplest Errorbar

    Code Explanation:

    • We import the required modules.
    • x and y are the lists containing the data points on the axes.
    • matplotlib.pyplot.title(), matplotlib.xlabel() and matplotlib.ylabel() are used to add more detail to the plot.
    • matplotlib.pyplot.errorbar() takes at least two parameters (x and y data points) to add error bars to the plot. The error axes plotted on each coordinate are the xerr and yerr.
    • matplotlib.pyplot.grid() and matplotlib.pyplot.show() are used to add grid to the plot and display the plot respectively.

    Example2: Error Bar with x-error Axis Only

    # This code is written in python
    # Importing the required module
    import matplotlib.pyplot as plt
    import random
    # x and y data points
    x=[1,2,3,4,5,6]
    y=[1,5,4,3,7,8]
    
    x_error= [random.uniform(1,2) for i in range(6)]
    plt.title("Error bar with only xerror axis")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.plot(x,y)
    
    # function to plot errorbar with the line plots
    plt.errorbar(x,y,xerr=x_error,ecolor='r',elinewidth=5,fmt='s',color='k')
    plt.grid()
    plt.show()
    

    Output:

    Error bar with x-error axis only

    Code explanation:

    • Importing the required modules.
    • x and y list containing data points.
    • y_error list contains random floats ranging from 1 to 2, random floats are generated using random.uniform().
    • matplotlib.pyplot.title(), matplotlib.pyplot.xlabel() and matplotlib.pyplot.ylabel() is used to add details to the figure.
    • matplotlib.pyplot.errorbar() used to plot the error bar on the markers where ecolor is red, elinewidth is 5, fmt is square, color is black, and xerr is a list containing the length of each error x-axis at each coordinate.

    Example3: Error Bar ith y-error Axis Only

    # This code is written in python
    # Importing the required module
    import matplotlib.pyplot as plt
    
    # x and y data points
    x=[1,2,3,4,5,6]
    y=[1,5,4,3,7,8]
    
    y_error= [random.uniform(1,2) for i in range(6)]
    plt.title("Error bar with only yerror axis")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.plot(x,y)
    
    # function to plot errorbar with the line plots
    plt.errorbar(x,y,yerr=y_error,ecolor='r',elinewidth=5,fmt='s',color='k')
    plt.grid()
    plt.show()
    

    Output:

    Function to plot errorbar

    Code Explanation:

    • Importing the required modules.
    • x and y list containing data points.
    • y_error list contains random floats ranging from 1 to 2; random floats are generated using random.uniform().
    • matplotlib.pyplot.title(), matplotlib.pyplot.xlabel() and matplotlib.pyplot.ylabel() is used to add details to the figure.
    • matplotlib.pyplot.errorbar() used to plot the error bar on the markers where ecolor is red, elinewidth is 5, fmt is square, color is black, and yerr is a list containing the length of each error y-axis at each coordinate.

    Example4: Interactive Error Bar in Matplotlib

    # This code is written in python
    # Importing the required module
    import matplotlib.pyplot as plt
    
    # x and y data points
    x=[1,2,3,4,5,6]
    y=[1,9,2,8,3,7]
    
    # Change the size of the figure
    plt.rcParams["figure.figsize"] = (10,6) 
    plt.title("Interactive error bar")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.plot(x,y)
    
    # function to plot errorbar with the line plots with more parameters
    plt.errorbar(x,y,xerr=0.5,yerr=1,fmt='s',color='brown',ecolor='green',elinewidth=4,capsize=5)
    plt.grid()
    plt.show()
    

    Output:

    Error bar with y-error axis only

    Code explanation:

    • Importing the required module.
    • x and y are the lists containing the data points on the axes.
    • matplotlib.pyplot.rcparams[‘figure.figsize’] is used to change the size of the figure.
    • matplotlib.errorbar() used to draw errorbar at each coordinates.
      • xerr and yerr are 0.5 and 1, respectively (length of error axes).
      • fmt: change the style of the marker. Set it to square.
      • ecolor: change the color of the errorbar. Set it to green.
      • color: change the color of the marker. Set it to brown.
      • elinewidth: set the error line width to 4.
      • capsize: set the capsize of errorbar to 5.

    Example5: Scatter Plot With Error Bars

    # This code is written in python
    # Importing required modules
    import matplotlib.pyplot as plt
    import random
    
    # x and y data points
    x= [1,3,5,6,7,8,9,10,11]
    y= [6, 5, 2, 12,15,7,8,10,11]
    
    # Generating array of xerr and yerr of random floats
    x_error = [random.uniform(1,3) for i in range(9)]
    y_error = [random.uniform(1,3) for i in range(9)]
    
    plt.scatter(x,y)
    
    # Plot error bar
    plt.errorbar(x, y, xerr = x_error, yerr = y_error,
                 fmt='s', ecolor = 'black',color='red')
    
    plt.title("Scatter plot with error bars")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.grid()
    plt.show()
    

    Output:

    Scatter plot with error bars

    Code explanation:

    • Importing the required module.
    • List x and y contain data points of the axes.
    • random.uniform() is used to generate a float in a range, with for loop we can generate multiples random floats.
    • matplotlib.scatter() is used to generate a scatter plot.
    • matplotlib.errorbar() generates error bars at each marker. The marker shape is square, and the error line color is black. The marker color is red.

    Example6: Error bar in a bar graph

    # This code is written in python
    # Importing required modules
    import matplotlib.pyplot as plt
    import random
    import numpy as np
    # x and y data points
    x= [1,2,3,4,5,6,7,8,9,10]
    y=[random.randint(0,20) for i in range(10)]
    
    
    # Generating array of xerr and yerr of random floats
    x_error = [random.uniform(0,1) for i in range(10)]
    y_error = [random.uniform(0,1) for i in range(10)]
    
    plt.bar(x,y,width=0.3)
    
    # Plot error bar
    plt.errorbar(x, y, xerr = x_error, yerr = y_error,
                 fmt='s', ecolor = 'black',color='red')
    
    plt.title("bar plot with error bars")
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.grid()
    plt.show()
    

    Output:

    Error bar in a bar graph

    Code explanation:

    • Importing the required modules
    • List x and y contain data points of the axes.
    • random.uniform() is used to generate floats.
    • matplotlib.pyplot.bar() is used to generate bar graph and width of bars is 0.3.
    • matplotlib.errorbar() is used to generate error bars at each marker; marker shape is square, error lines color is black and marker color is red.

    Conclusion

    • Error bars in matplotlib are y vs. x planes generated at each coordinate to show the standard deviation and irregularities in the data.
    • matplotlib.pyplot.errorbar() is the function required to generate error bars.
    • This function takes at least two parameters,xand y data points, and other parameters are for modifying the properties of marker and error axes.
    • Matplotlib error bar return ErrorbarContainer.

    In this article, we learn about the Matplotlib errorbar in Python. The Pyplot module of the Matplotlib library provides MATLAB like interface. And the matplotlib.pyplot.errorbar() function plots y versus x as lines and/or markers with attached errorbars. Moreover, Error bars help to indicate estimated error or uncertainty to give a general sense of how precise a measurement is; this is done through the use of markers drawn over the original graph and its data points. Before we look into examples of Matplotlib errobars and errorbar graphs, let me brief you with the syntax and return the same.

    Syantax of matplotlib errorbar()

    matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=”, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)

    Parameters of Matplotlib Errorbar:

    • x, y: The horizontal and vertical coordinates of the data points.
    • fmt: Contains the string value (Optional)
    • xerr, yerr: An array containing errors, and the errors must be positive values.
    • ecolor: (default: NONE) In simple words, it’s the color of the errorbar lines. (Optional)
    • elinewidth: Linewidth of the errorbar lines with default value NONE. (Optional)
    • capsize: Length of the error bar caps in points with default value NONE. (Optional)
    • barsabove: (default: False)Contains boolean values for plotting error bars above the plot symbols. (Optional)
    • lolims, uplims, xlolims, xuplims: Contains boolean values, which indicate that a value gives only upper/lower limits. (Optional) errorevery: Contain integer values that help draws error bars on a subset of the data. (Optional)

    Return type of Matplotlib Errorbar:

    The Matplotlib errorbar() function returns a container having:
    plotline: Line2D instance of x, y plot markers and/or line.
    caplines: Tuple of Line2D instances of the error bar caps.
    barlinecols: Tuple of LineCollection with the horizontal and vertical error ranges.

    Example of Matplotlib Errorbar in Python

    Errorbar helps you to understand the nature of graphs and their convergence. The errorbar can give an idea about the graph’s variance with its mean. Correspondingly, you can identify the outliers from your graph and take care of them. Moreover, it represents uncertainty in your graph.

    import numpy as np 
    import matplotlib.pyplot as plt 
      
    xval = np.arange(0.1, 4, 0.5) 
    yval = np.exp(-xval) 
      
    plt.errorbar(xval, yval, xerr = 0.4, yerr = 0.5) 
      
    plt.title('matplotlib.pyplot.errorbar() function Example') 
    plt.show() 
    

    OUTPUT:

    Example of Matplotlib Errorbar in Python

    EXPLANATION:

    Firstly, the above example is a fundamental implementation of the Matplotlib errorbar() function. The ‘xval’ and ‘yval’ contains the horizontal and vertical coordinates of the data points required for errorbar plotting. In addition, the ‘xerr’ and ‘yerr’ are arguments to the errorbar function. The values assigned to them are 0.4 and 0.5, respectively, the positive error values. Finally, these four parameters passed to the errorbar() function are mandatory arguments required to plot any Python errorbars.

    Matplotlib Errorbar in Python Multiple lines

    It’s very important to be able to plot multiple lines in the same graphs. In the following example, we’ll plot multiple errorbars in the same graph.

    import numpy as np 
    import matplotlib.pyplot as plt 
       
    fig = plt.figure() 
    x = np.arange(10) 
    y = 3 * np.sin(x / 20 * np.pi) 
    yerr = np.linspace(0.05, 0.2, 10) 
       
    plt.errorbar(x, y + 7, yerr = yerr, 
                 label ='Line1') 
    plt.errorbar(x, y + 5, yerr = yerr, 
                 uplims = True,  
                 label ='Line2') 
    plt.errorbar(x, y + 3, yerr = yerr,  
                 uplims = True,  
                 lolims = True, 
                 label ='Line3') 
      
    upperlimits = [True, False] * 5
    lowerlimits = [False, True] * 5
    plt.errorbar(x, y, yerr = yerr, 
                 uplims = upperlimits,  
                 lolims = lowerlimits, 
                 label ='Line4') 
       
    plt.legend(loc ='upper left') 
      
    plt.title('matplotlib.pyplot.errorbar() 
    function Example') 
    plt.show() 
    

    OUTPUT:

    Errorbar in Python Multiple lines

    EXPLANATION:

    Firstly, in the above example, the matplotlib errorbar() function creates multiple errorbar lines. The x and y defined are the coordinates of the data points. Along the y-axis, graph plot error. Hence only ‘yerr’ is specified for each line. Additionally, the upper and lower limits indicate the values for only upper and lower limits. Also, the label is an argument indicating the lines as Line1, Line2, etc.

    Errorbar graph with error in x

    import matplotlib.pyplot as plt  
      
    # making a simple plot 
    x =[1, 2, 3, 4, 5, 6, 7] 
    y =[1, 2, 1, 2, 1, 2, 1] 
      
    # creating error 
    x_error = 0.5
      
    # ploting graph 
    plt.plot(x, y) 
    plt.errorbar(x, y, 
                 xerr = x_error, 
                 fmt ='o') 
    

    OUTPUT:

    Errorbar graph with error in x

    EXPLANATION:

    Firstly, in the above example, x and y are arrays defined containing x and y coordinates to plot the graph. Additionally, the ‘x_error’ is 0.5, which introduces errors only along the x-axis. The x, y, and xerr are the mandatory parameters passed to the Matplotlib errorbar in Python. The optional parameter ‘fmt’ containing string value is also passed.

    Errorbar graph with error in y

    import matplotlib.pyplot as plt  
      
      
    # making a simple plot 
    x =[1, 2, 3, 4, 5, 6, 7] 
    y =[1, 2, 1, 2, 1, 2, 1] 
      
    # creating error 
    y_error = 0.2
      
    # ploting graph 
    plt.plot(x, y) 
      
    plt.errorbar(x, y, 
                 yerr = y_error, 
                 fmt ='o') 
    

    OUTPUT:

    Errorbar graph with error in y

    EXPLANATION:

    Firstly, in the above example, x and y are arrays defined containing x and y coordinates to plot the graph. The ‘y_error’ is 0.2, which introduces errors only along the y-axis. The x, y, and yerr are the mandatory parameters passed to the errorbar function. The optional parameter ‘fmt’ containing string value is also passed.

    Errorbar graph with Variable error in x and y

    import matplotlib.pyplot as plt 
      
    x =[1, 2, 3, 4, 5] 
    y =[1, 2, 1, 2, 1] 
      
    y_errormin =[0.1, 0.5, 0.9, 
                 0.1, 0.9] 
    y_errormax =[0.2, 0.4, 0.6,  
                 0.4, 0.2] 
      
    x_error = 0.5
    y_error =[y_errormin, y_errormax] 
      
    # ploting graph 
    # plt.plot(x, y) 
    plt.errorbar(x, y, 
                 yerr = y_error, 
                 xerr = x_error,  
                 fmt ='o') 
    

    OUTPUT:

    Errorbar graph with Variable error in x and y

    EXPLANATION:

    The above example depicts an error bar graph plot for variable errors. Likewise, the x and y are two arrays defined containing the coordinate points. The error along the x-axis is 0.5. Simultaneously, the error along the y-axis between two arrays is y_errormin and y_errormax. These parameters are arguments to the Matplotlib errorbar function to get the desired output.

    Conclusion

    This article clearly presents to you different ways of using the Matplotlib errorbar in Python. Examples of both errorbar lines and graphs are provided with a detailed explanation. Errorbars provide an additional layer of detail on the presented data. Refer to this article for any queries related to the Matplotlib errorbar() function.

    However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

    Happy Pythoning!

    In this tutorial we explain how show the error bar in Matplotlib graphs (matplotlib errorbar). Python. The error bar, is a bar that indicates the error of some measurement. It is widely used in statistics, mainly in scatter diagrams.

    Adding the error bar in Matplotlib, Python.

    It´s very simple, we just have to write the value of the error.

    We use the command:

    plt.errorbar(x, y, yerr  = 2, capsize = 3)

    Where:

    • x, are the data of the X axis.
    • y, are the data of the Y axis.
    • yerr, is the error value of the Y axis. Each point has its own error value.
    • xerr, is the error value of the X axis.
    • capsize, is the size of the lower and upper lines of the error bar.

    A simple example, where we only plot one point. The error is the 10 % on the Y axis.

    import matplotlib.pyplot as plt
    x = 1
    y = 20
    y_error = 20*0.10             ## El 10% de error
    
    plt.errorbar(x,y, yerr = y_error, capsize = 3)
    plt.show()

    Here is an asymmetric example.

    We will explain it later.

    Matplotlib errorbar example.

    Now a slightly more complex example. Here we will use the numpy library to generate the arrays that will be ploted.

    First we generate the data in X and Y.

    Next, we generate the error of each point.

    Then we plot using the command “plt.errorbar (…)”, giving it the desired characteristics.

    The code is the following:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(1,8)
    y = np.array([20,10,45,32,38,21,27])
    y_error = y * 0.10    ##El 10%
    
    plt.errorbar(x, y,  yerr = y_error, linestyle="None”,  fmt="ob",  capsize=3,  ecolor="k")
    plt.show()
    

    Parameters of the errorbar:

    • yerr, is the error value in each point.
    • linestyle, here we indicate that we will not plot a line.
    • fmt, it is the type of marker, in this case is a point (“o”) blue (“b”).
    • capsize, is the size of the lower and upper lines of the error bar.
    • ecolor, is the color of the error bar. The default color is the marker color.

    Note: We can combine “plt.plot” and “plt.errorbar” if we think necessary.

    Errorbar no line python

    Matplotlib errorbar no line.

    If we want not plot a line using “plt.errorbar (…)“, we use the parameter linestyle = “None”.

    plt.errorbar(x, y,  yerr = y_error, linestyle="None”,  fmt="ob",  capsize=3,  ecolor="k")

    We can edit the errorbar, adding lower and upper lines or changing the thickness.

    plt.errorbar(x, y,  yerr = y_error, linestyle="None”,  fmt="ob",  capsize=3,  ecolor="k")

    Command capsize, Matplotlib.

    This command indicates the length of the cap lines of the error bar. If we do not use it, by default the length will be 0 and we will not see lines at the end.

    Command capthick, Matplotlib.

    This command indicates the width of the cap lines of the error bars.

    Matplolib errorbar color.

    We can edit the color of the errorbar in Matplotlib, using the “ecolor” parameter.

    plt.errorbar(x, y,  yerr = y_error, linestyle="None”,  fmt="ob",  capsize=3,  ecolor="k")

    If we omit this parameter, the color of the error bar will be the same as the marker.

    We have several colors to choose:

    k, black

    b, blue

    g, green

    r, red

    y, yellow

    You can see more colors here:

    Python matplotlib colores predeterminados y hexadecimal.

    Matplolib errorbar asymetric.

    An asymmetric error bar does not have the same error on each side. This can be done very easily in Python using matplotlib.

    We only need to modify the error and do it with 2 values, something like this:

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.arange(1,8)
    y = np.array([20,10,45,32,38,21,27])
    
    y_error = [y * 0.05, y*0.1]  ##El 5% en un lado y el 10% en el otro
    
    plt.errorbar(x,y, linestyle="None", yerr = y_error, fmt="ob", capsize=7, ecolor="k")
    plt.show()
    

    Matplotlib errorbar style, Python.

    We have already seen several parameters, this is a summary:

    • Fmt, it is the type of marker, in this case is a point (“o”) blue (“b”).
    • Linestyle, here we indicate that we will not plot a line.
    • Ecolor, is the color of the error bar. The default color is the marker color.
    • Elinewidth, is the width of the error bar.
    • Capsize, is the size of the lower and upper lines of the error bar.
    • capthick, indicates the width of the cap lines of the error bars.
    • Barsabove, is True of False.

    Errorbar Python examples, Matplotlib.

    Here are two examples for a graph with error bars in Python, using Matplotlib.

    We include some parameters that were not explained before. The “plt.errorbar (…)” command uses almost all the parameters that are used in the “plt.plot (…)”command.

    import matplotlib.pyplot as plt
    import numpy as np
    x = np.arange(1,8)
    y = np.array([20,10,45,32,38,21,27])
    y_error = y * 0.10  ##El 10%
    
    plt.errorbar(x, y,  linestyle=":",  yerr = y_error,  fmt="sb",  markersize=9, capsize=3,  ecolor="k",  barsabove=True)
    plt.show()

    import matplotlib.pyplot as plt
    import numpy as np
    x = np.arange(1,8)
    y = np.array([20,10,45,32,38,21,27])
    
    y_error = y * 0.10  ##El 10%
    
    plt.errorbar(x, y, linestyle="None", yerr = y_error, fmt="or", markersize=9, capsize=7, ecolor="b", elinewidth=3)
    plt.show()

    Official page reference.

    matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs) [source]

    Plot y versus x as lines and/or markers with attached errorbars.

    x, y define the data locations, xerr, yerr define the errorbar sizes. By default, this draws the data markers/lines as well the errorbars. Use fmt=’none’ to draw errorbars without any data markers.

    Parameters:
    x, y : scalar or array-like

    The data positions.

    xerr, yerr : scalar or array-like, shape(N,) or shape(2,N), optional

    The errorbar sizes:

    • scalar: Symmetric +/- values for all data points.
    • shape(N,): Symmetric +/-values for each data point.
    • shape(2,N): Separate — and + values for each bar. First row
      contains the lower errors, the second row contains the upper errors.
    • None: No errorbar.

    Note that all error arrays should have positive values.

    See Different ways of specifying error bars for an example on the usage of xerr and yerr.

    fmt : plot format string, optional, default: ''

    The format for the data points / data lines. See plot for details.

    Use ‘none’ (case insensitive) to plot errorbars without any data markers.

    ecolor : mpl color, optional, default: None

    A matplotlib color arg which gives the color the errorbar lines. If None, use the color of the line connecting the markers.

    elinewidth : scalar, optional, default: None

    The linewidth of the errorbar lines. If None, the linewidth of the current style is used.

    capsize : scalar, optional, default: None

    The length of the error bar caps in points. If None, it will take the value from rcParams["errorbar.capsize"].

    capthick : scalar, optional, default: None

    An alias to the keyword argument markeredgewidth (a.k.a. mew). This setting is a more sensible name for the property that controls the thickness of the error bar cap in points. For backwards compatibility, if mew or markeredgewidth are given, then they will over-ride capthick. This may change in future releases.

    barsabove : bool, optional, default: False

    If True, will plot the errorbars above the plot symbols. Default is below.

    lolims, uplims, xlolims, xuplims : bool, optional, default: False

    These arguments can be used to indicate that a value gives only upper/lower limits. In that case a caret symbol is used to indicate this. lims-arguments may be of the same type as xerr and yerr. To use limits with inverted axes, set_xlim() or set_ylim() must be called before errorbar().

    errorevery : positive integer, optional, default: 1

    Subsamples the errorbars. e.g., if errorevery=5, errorbars for every 5-th datapoint will be plotted. The data plot itself still shows all data points.

    Returns:
    container : ErrorbarContainer

    The container contains:

    • plotline: Line2D instance of x, y plot markers and/or line.
    • caplines: A tuple of Line2D instances of the error bar caps.
    • barlinecols: A tuple of LineCollection with the horizontal and vertical error ranges.
    Other Parameters:
    **kwargs

    All other keyword arguments are passed on to the plot command for the markers. For example, this code makes big red squares with thick green edges:

    x,y,yerr = rand(3,10)
    errorbar(x, y, yerr, marker='s', mfc='red',
             mec='green', ms=20, mew=4)
    

    where mfc, mec, ms and mew are aliases for the longer property names, markerfacecolor, markeredgecolor, markersize and markeredgewidth.

    Valid kwargs for the marker properties are Lines2D properties:

    Property Description
    agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
    alpha float
    animated bool
    antialiased or aa bool
    clip_box Bbox
    clip_on bool
    clip_path [(Path, Transform) | Patch | None]
    color or c color
    contains callable
    dash_capstyle {‘butt’, ’round’, ‘projecting’}
    dash_joinstyle {‘miter’, ’round’, ‘bevel’}
    dashes sequence of floats (on/off ink in points) or (None, None)
    drawstyle or ds {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’
    figure Figure
    fillstyle {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}
    gid str
    in_layout bool
    label object
    linestyle or ls {‘-‘, ‘—‘, ‘-.’, ‘:’, », (offset, on-off-seq), …}
    linewidth or lw float
    marker marker style
    markeredgecolor or mec color
    markeredgewidth or mew float
    markerfacecolor or mfc color
    markerfacecoloralt or mfcalt color
    markersize or ms float
    markevery None or int or (int, int) or slice or List[int] or float or (float, float)
    path_effects AbstractPathEffect
    picker float or callable[[Artist, Event], Tuple[bool, dict]]
    pickradius float
    rasterized bool or None
    sketch_params (scale: float, length: float, randomness: float)
    snap bool or None
    solid_capstyle {‘butt’, ’round’, ‘projecting’}
    solid_joinstyle {‘miter’, ’round’, ‘bevel’}
    transform matplotlib.transforms.Transform
    url str
    visible bool
    xdata 1D array
    ydata 1D array
    zorder float

    Notes

    Note

    In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[<arg>]:

    • All arguments with the following names: ‘x’, ‘xerr’, ‘y’, ‘yerr’.

    Objects passed as data must support item access (data[<arg>]) and membership test (<arg> in data).

    Examples using matplotlib.pyplot.errorbar

    Понравилась статья? Поделить с друзьями:
  • Pls 801 internal error
  • Pls 00306 ошибочно число или типы аргументов при обращении к
  • Plpgsql raise error
  • Plotting error non numeric vertex definition
  • Plotting error empty plot maple