Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

matlab errorbar: Syntax, Plots and Customization

Master the MATLAB errorbar function to display experimental uncertainties, standard deviations, and confidence intervals across line plots and grouped charts.

Written and maintained by CASRAI Editorial Board

Last updated

In MATLAB, the errorbar function plots datasets with horizontal or vertical uncertainty markers attached to each observation point. Researchers, laboratory scientists, and quantitative analysts use error bars to visualize measurement uncertainty, dispersion, and statistical confidence across experimental trials. Whether illustrating standard deviations in biological replicates, standard errors of the mean (SEM) in clinical cohorts, or 95% confidence intervals from regression models, the errorbar matlab command provides fine-grained control over line styles, data markers, asymmetrical bounds, and grouped bar chart overlays.

This guide explains the official syntax for symmetric and asymmetric uncertainty, demonstrates how to suppress connecting lines for discrete scatter plots, shows how to accurately align error bars with grouped categorical bars, and details the statistical standards required for transparent scientific publication.

What it is used for in research

Error bars are an indispensable visual tool in quantitative research, bridging raw experimental data and inferential statistics. In peer-reviewed scientific literature, plotting a mean value alone obscures experimental variance, measurement error, and underlying sample size. The errorbar function provides a standardized method to display these statistical intervals directly over data points.

In research reporting, error bars typically communicate one of three distinct statistical metrics:

  • Standard Deviation (SD): Quantifies the dispersion or variability of individual measurements around the sample mean. SD reflects the spread of the underlying data distribution and does not shrink as sample size increases.
  • Standard Error of the Mean (SEM): Quantifies the precision of the sample mean as an estimate of the true population mean, computed as the standard deviation divided by the square root of the sample size (SEM = SD / √N). SEM decreases as sample size increases.
  • Confidence Intervals (CI): Represents an inferential interval—most commonly a 95% confidence interval—calculated from the standard error and critical t-distribution values. A 95% CI provides an estimated range likely to contain the true population parameter under repeated sampling.

Adhering to reporting guidelines from major academic bodies and journals (including Nature Portfolio, APA, and ICMJE) requires authors to explicitly state what error bars represent, report the exact sample size (N), and clarify whether error bars represent independent biological replicates or repeated technical measurements. Incorporating precise uncertainty bounds is essential for experimental reproducibility, allowing peer reviewers and independent laboratories to evaluate whether observed effect sizes exceed experimental noise. For continuous analytical models, error bars also inform weighted curve fitting; for parameter estimation workflows, see our dedicated guide on Fit in MATLAB: polyfit, fit and fittype.

Install or access

The errorbar function is a built-in feature of core MATLAB and does not require supplementary commercial add-ons or specialized application toolboxes. Researchers can access MATLAB through several official MathWorks deployment pathways:

  • Institutional and Campus-Wide Licenses: Most universities, national laboratories, and research institutions provide authenticated access to MATLAB through institutional single sign-on via the MathWorks portal.
  • Local Desktop Installation: The MATLAB desktop environment runs natively on 64-bit Windows, macOS (both Apple silicon and Intel architectures), and Linux distributions. The plotting engine uses local hardware acceleration (OpenGL) to render interactive graphics figures.
  • MATLAB Online: Users can run MATLAB scripts and generate graphics directly in modern web browsers via the cloud-hosted environment at matlab.mathworks.com, storing figures and datasets in MathWorks Cloud storage.
  • Command-Line and Batch Execution: For high-performance computing (HPC) clusters or automated analysis pipelines, MATLAB scripts containing errorbar commands can be executed in non-interactive batch mode (matlab -batch "run_script"), saving generated figures directly to vector (PDF, EPS) or raster (PNG, TIFF) image formats.

Step-by-step task

The following numbered steps demonstrate the core plotting workflow, progressing from basic symmetric error bars to discrete point markers, asymmetric bounds, and grouped categorical bar charts.

Step 1: Prepare Sample Data and Summary Statistics

Begin by organizing independent variables (X), central response means (Y), and corresponding uncertainty metrics (such as SEM or SD). Ensure all vectors share identical dimensions:

% Define independent conditions and response measurements
x = 1:5;
y = [14.2, 19.8, 16.5, 24.1, 28.7];

% Compute or assign standard error of the mean (SEM)
err_sem = [1.2, 1.5, 0.8, 1.9, 1.4];

Step 2: Generate Basic Symmetric Error Bars

Call errorbar(x, y, err) to generate a line plot where each vertical error bar extends a distance of err(i) above and below each observation (x(i), y(i)), yielding a total whisker length of 2 * err(i):

figure;
e = errorbar(x, y, err_sem);
xlabel('Experimental Condition');
ylabel('Observed Mean Response (a.u.)');
title('Response Across Experimental Conditions');

Step 3: Suppress Connecting Lines for Discrete Scatter Observations

In many experimental studies, conditions represent categorical or discrete experimental treatments where continuous connecting lines are misleading. To display standalone data markers with error bars, set 'LineStyle' to 'none' and specify a marker symbol:

figure;
e = errorbar(x, y, err_sem, 'o', 'LineStyle', 'none', 'LineWidth', 1.5, 'MarkerSize', 7);
e.Color = [0.2 0.2 0.2];             % Dark gray line and marker edge
e.MarkerFaceColor = [0.2 0.6 0.9];   % Blue filled marker
e.CapSize = 8;                       % Cap width in points
xlabel('Treatment Cohort');
ylabel('Assay Signal (nm)');
grid on;

To inspect available styling options, line widths, and dash formatting, consult our overview of MATLAB LineStyle: Values, Syntax and Cycling.

Step 4: Plot Asymmetrical Error Bars

When displaying skewed distributions, non-parametric percentiles, or log-transformed confidence intervals, lower and upper deviations often differ. Pass separate vectors for the lower bound (yneg) and upper bound (ypos):

% Asymmetric deviations: yneg is distance below, ypos is distance above
y_neg = [0.9, 1.2, 0.6, 1.4, 1.1];
y_pos = [2.1, 2.5, 1.8, 2.8, 2.3];

figure;
e_asym = errorbar(x, y, y_neg, y_pos, 's', 'LineStyle', 'none', 'LineWidth', 1.2);
e_asym.MarkerFaceColor = [0.85 0.35 0.1];
e_asym.CapSize = 6;
xlabel('Trial Block');
ylabel('Measurement (Median with Interquartile Range)');

Step 5: Overlay Error Bars on Grouped Bar Charts

A frequent challenge in laboratory reporting is placing error bars on grouped bar charts. MATLAB’s bar function creates a series of Bar objects whose individual bar center x-coordinates are accessible through the XEndPoints property:

% Matrix of group means: 3 experimental conditions across 2 genotypes
group_means = [12.5, 18.2; 15.0, 22.4; 11.8, 16.9];
group_sems  = [1.1,  1.4;  1.2,  1.6;  0.9,  1.3];

figure;
b = bar(group_means, 'grouped');
hold on;

% Loop through each series in the grouped bar chart
for k = 1:size(group_means, 2)
    % Extract exact x-coordinates for the individual bars
    x_positions = b(k).XEndPoints;
    errorbar(x_positions, group_means(:, k), group_sems(:, k), ...
             'k.', 'LineStyle', 'none', 'LineWidth', 1.2, 'CapSize', 6);
end
hold off;

set(gca, 'XTickLabel', {'Basal', 'Stimulated', 'Inhibited'});
ylabel('Enzyme Activity (μmol/min)');
legend({'Wild Type', 'Knockout'}, 'Location', 'NorthWest');

Step 6: Encapsulate Custom Plotting Logic in Reusable Functions

To ensure automated batch plotting across large datasets or multi-animal studies, wrap your error-plotting routine into a modular function. Refer to our guide on how to Declare a Function in MATLAB to structure clean parameter validation and handle graphics outputs.

Output and how to read it

When executing errorbar, MATLAB returns an ErrorBar graphics object that encapsulates the visual elements of the plot:

  • Data Marker: Represents the central tendency (sample mean or median). By default, markers are unset when connecting lines are active; specifying a marker like 'o', 's', or '^' makes point locations explicit.
  • Whiskers: The vertical or horizontal line segments extending from the central marker. For symmetric plots, the segment spans y - err to y + err.
  • Caps: The horizontal (or vertical) crossbars at the terminal ends of the error bars. Cap width is calibrated in points via the CapSize property (default is 6 points). Setting CapSize = 0 eliminates caps entirely, creating clean, modern lines favored in multi-series plots.

When interpreting published error plots, readers and reviewers must adhere to statistical guidelines:

  • Inferential Significance from Overlap: Avoid assuming that overlapping SEM error bars indicate lack of statistical significance, or that non-overlapping SEM bars confirm statistical significance (p under 0.05). For independent two-sample comparisons, SEM bars can be separated by a noticeable gap even when differences fail to reach significance, whereas 95% confidence intervals typically require an overlap of approximately half the average arm length to correspond to p ≈ 0.05.
  • Transparency in Figure Captions: All scientific manuscripts must clearly document the statistical definition of the error bars in the figure caption (e.g., “Values represent Mean ± SEM, N = 6 independent biological experiments”). Depositing raw numerical values and plotting code in an open data repository ensures full computational auditability.

Troubleshooting

Dimension Mismatch: “Vectors must be the same length”

Cause: The coordinates x, y, and the error matrices (err, yneg, ypos) have incompatible sizes or mixed row-and-column orientations (e.g., 1xN row vector vs. Nx1 column vector).

Solution: Enforce matching dimensions across all input vectors before calling errorbar. Using the colon operator (:) guarantees consistent column orientation:

x = x(:);
y = y(:);
err = err(:);
errorbar(x, y, err);

Unwanted Continuous Lines Connecting Discrete Categories

Cause: By default, MATLAB’s errorbar function draws a continuous line connecting adjacent points, assuming time-series or functional dependence.

Solution: Explicitly pass 'LineStyle', 'none' in the command arguments, or set the property on the returned handle:

e = errorbar(x, y, err);
e.LineStyle = 'none';
e.Marker = 'o';

Disappearing Error Bars or Warnings on Logarithmic Axes

Cause: When setting logarithmic scaling on the vertical axis (set(gca, 'YScale', 'log')), any lower error whisker that extends below zero (y - err ≤ 0) produces an invalid mathematical value (log of zero or negative numbers). MATLAB will either drop the entire lower whisker or issue graphics clipping warnings.

Solution: Use asymmetric error bar syntax (errorbar(x, y, yneg, ypos)) with mathematically bounded lower limits, or transform your data into log-space prior to computing symmetric uncertainty in log units:

% Ensure lower error bound does not cross zero into non-positive space
yneg_clipped = min(err, y * 0.99);
errorbar(x, y, yneg_clipped, err, 'o', 'LineStyle', 'none');
set(gca, 'YScale', 'log');

Error Bars Centered Inaccurately on Grouped Bar Charts

Cause: Passing group indices (e.g., 1:num_groups) to errorbar centers uncertainty ticks at the midpoint of the categorical cluster rather than above the individual grouped bars.

Solution: Query the XEndPoints property of each Bar object created by bar(), which provides the exact floating-point center of each bar column within the cluster.

Free alternatives

For research groups seeking open-source computational environments or reproducible command-line pipelines without proprietary licensing dependencies, several mature alternatives support identical or expanded error-plotting functionality:

Software / Library Function / Syntax License Key Research Strengths Ecosystem Fit
GNU Octave errorbar(x, y, err) GPLv3 (Free and Open Source) Near 100% MATLAB m-file syntax compatibility; natively runs existing MATLAB error-bar scripts without modification. Numerical computing, drop-in replacement for laboratory compute nodes.
Python (Matplotlib) plt.errorbar(x, y, yerr=err, xerr=None) PSF License (Permissive) Fine-grained control over cap sizes (capsize), upper/lower limits (lolims, uplims), and error bar styling. General scientific computing, Jupyter notebooks, Scipy, Pandas workflows.
Python (Seaborn) sns.lineplot() / sns.barplot(errorbar='ci') BSD 3-Clause (Permissive) Automated computation of bootstrap confidence intervals (CI) and SEM directly from tidy DataFrames. Exploratory statistical analysis, publication-grade aesthetics.
R (ggplot2) geom_errorbar(aes(ymin=..., ymax=...)) MIT License (Permissive) Grammar of Graphics declarative syntax; clean layering over scatter plots, line graphs, and faceted bar charts. Academic statistical reporting, bioinformatics, biostatistics.
Julia (Plots.jl) plot(x, y, yerror=err) MIT License (Permissive) High performance; uniform syntax across multiple backends (GR, PyPlot, Plotly). Computational physics, differential equations, large-scale simulations.

Among these, GNU Octave provides the most seamless transition for existing MATLAB workflows, supporting errorbar(x, y, err), asymmetric bounds errorbar(x, y, lerr, uerr), and bidirectional error bars without code refactoring.

FAQ

How do you remove connecting lines between error bars in MATLAB?

To display discrete error bars without a connecting line, set the 'LineStyle' name-value argument to 'none' and specify a marker type, such as errorbar(x, y, err, 'o', 'LineStyle', 'none'). Alternatively, capture the returned graphics handle and set e.LineStyle = 'none'.

What is the difference between standard deviation and standard error in MATLAB plots?

Standard deviation (computed via std(y)) describes the natural variability or dispersion of individual data points within a sample. Standard error of the mean (SEM, calculated as std(y) / sqrt(length(y))) measures the precision of the estimated sample mean relative to the true population mean. Standard deviation describes sample spread, whereas SEM describes estimation precision.

How do you adjust the cap width of error bars in MATLAB?

Cap width is adjusted using the CapSize property on the ErrorBar graphics object, specified in typographic points (default is 6). For example, e = errorbar(x, y, err); e.CapSize = 10; increases cap width, while e.CapSize = 0; removes caps entirely for a modern, minimalist appearance.

How can you plot horizontal error bars in MATLAB?

To plot horizontal error bars, use the 'horizontal' orientation flag: errorbar(x, y, xerr, 'horizontal'). To plot simultaneous horizontal and vertical uncertainty bounds, pass four error arguments: errorbar(x, y, yneg, ypos, xneg, xpos).

Can you use errorbar with grouped bar charts?

Yes. Create the grouped bar chart using b = bar(data, 'grouped'), then retrieve the exact horizontal coordinates for each bar series using b(k).XEndPoints. Pass these coordinates into errorbar(b(k).XEndPoints, data(:, k), errors(:, k), '.', 'LineStyle', 'none') with hold on active.

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about matlab errorbar: Syntax, Plots and Customization

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →