Skip to content

MATLAB - Plotting Error Bars

MATLAB - Visualizing Data Uncertainty with Error Bars

Section titled “MATLAB - Visualizing Data Uncertainty with Error Bars”

In scientific and statistical analysis, data points are often estimates that carry some degree of uncertainty. Error bars are a graphical representation of this variability, providing a visual cue to the reliability of the data. They are essential for communicating results transparently, typically representing measures like standard deviation, standard error, or confidence intervals.

MATLAB’s errorbar function is a versatile tool for creating line plots that include these crucial visual elements.

The errorbar function allows for a wide range of customizations, from simple symmetric errors to complex, two-dimensional error representations.

  • errorbar(y, err): Plots vector y and adds a symmetric vertical error bar of length 2*err(i) at each point y(i).
  • errorbar(x, y, err): Plots y versus x with symmetric vertical error bars.
  • errorbar(x, y, neg, pos): Plots y versus x with asymmetric vertical error bars. neg specifies the length below each point, and pos specifies the length above.
  • errorbar(x, y, yneg, ypos, xneg, xpos): Plots with both vertical (asymmetric yneg, ypos) and horizontal (asymmetric xneg, xpos) error bars.
  • errorbar(___, 'horizontal'): Creates horizontal instead of vertical error bars.
  • e = errorbar(___): Creates the plot and returns an ErrorBar object e. This object handle is key for programmatic customization after the plot is created.

Let’s see how these syntaxes work in practice. The following code examples are self-contained and ready to run.

Plotting experimental results with their standard deviation.

% Sample data: monthly average temperatures and standard deviations
months = 1:6;
yData = [5.5, 8.2, 12.1, 15.8, 18.0, 21.3]; % Mean temperature
yError = [1.2, 1.5, 1.3, 1.8, 1.6, 1.9]; % Standard deviation
figure; % Create a new figure window
errorbar(months, yData, yError);
title('Monthly Average Temperature with Standard Deviation');
xlabel('Month');
ylabel('Temperature (°C)');
grid on;

Expected Output Description: This code generates a line plot showing a rising temperature trend over six months. Each data point has a vertical error bar extending equally above and below it, representing the standard deviation for that month.

Example 2: Asymmetric and Styled Error Bars

Section titled “Example 2: Asymmetric and Styled Error Bars”

This example demonstrates asymmetric error bars and modern styling using name-value pairs.

% Data representing a growth process with different upper/lower bounds
xData = 1:5;
yData = [10, 18, 23, 25, 26];
lowerError = [1.5, 2.0, 2.5, 2.0, 1.8]; % Lower bound of error
upperError = [3.0, 3.5, 2.8, 2.2, 1.5]; % Upper bound of error
figure;
errorbar(xData, yData, lowerError, upperError, ...
'LineStyle', '--', ...
'Marker', 'o', ...
'MarkerFaceColor', 'blue', ...
'Color', 'black', ...
'CapSize', 10, ...
'LineWidth', 1.5);
title('Growth Process with Asymmetric Confidence Interval');
xlabel('Time Point');
ylabel('Measurement');

Expected Output Description: The resulting plot shows five data points connected by a dashed black line. Each point is a blue-filled circle. The vertical error bars are asymmetric, extending further up or down depending on the lowerError and upperError values. The ends of the error bars have caps of size 10 points.

Example 3: Programmatic Customization via Object Handle

Section titled “Example 3: Programmatic Customization via Object Handle”

Capturing the ErrorBar object handle allows you to modify the plot after its creation, which is useful for dynamic updates or complex styling.

% Data from two different experimental groups
x = 1:10;
group1_y = 2*x + randn(1,10);
group1_err = 0.5 * ones(1,10) + rand(1,10);
group2_y = 1.8*x + 1.5 + randn(1,10);
group2_err = 0.5 * ones(1,10) + rand(1,10);
figure;
hold on; % Allow multiple plots on the same axes
% Plot group 1 and get its handle
e1 = errorbar(x, group1_y, group1_err, 'b-o');
% Plot group 2 and get its handle
e2 = errorbar(x, group2_y, group2_err, 'r-s');
% Now, customize using the handles
e1.MarkerSize = 8;
e1.LineWidth = 2;
e1.DisplayName = 'Group 1';
e2.CapSize = 12;
e2.MarkerFaceColor = 'red';
e2.DisplayName = 'Group 2';
hold off;
legend('show');
title('Comparison of Two Experimental Groups');
xlabel('Dose');
ylabel('Response');
grid on;

Expected Output Description: This generates a plot with two distinct lines. The first line is solid blue with circle markers. The second is solid red with square markers, which are filled red and have larger end caps on their error bars. A legend correctly identifies ‘Group 1’ and ‘Group 2’, demonstrating how the object handles were used to set display names and other properties after the initial plot calls.

  • Always Label Your Error: In the plot’s caption or text, always state what your error bars represent (e.g., ‘Error bars represent the standard error of the mean, n=5’).
  • Use Name-Value Pairs: For styling, prefer explicit name-value pairs ('Color', 'red') over older LineSpec strings ('r') for better code readability and maintainability.
  • Check Dimensions: Ensure your data vectors (x, y) and error vectors (err, neg, pos) have the same number of elements to avoid errors.
  • Accessibility: For publication-quality or presentation graphics, use distinct markers, line styles, and high-contrast colors to ensure the plot is readable for everyone, including those with color vision deficiencies.