Plotting Error Bars in MATLAB
Error bars are a way of plotting errors on each point in a data set as vertical bars in a linear plot. MATLAB provides a simple function to plot the error bars for a given data; the errorbar() function.
Syntax:
errorbar(x,y,errors,…)
Where,
- x – contains x data
- y- contains y data
- error – contains errors for every point in y with respect to x.
Now, let us see the same in implementation with some examples.
Let us create error bars of equal length first.
Example 1:
Matlab
% MATLAB code for Plot a graph % X data x = 0.1*[1:35]; % Y data y = x.^2; error = 3*ones(size(y)); % Defining error bars of same length errorbar(x,y,error) |
Output:
We can change the error bars from vertical to horizontal.
Example 2:
Matlab
% MATLAB code for plot error bar % X data x = 1:2:23; % Y data y = x.^2; % Defining error bars of same length error = 3*ones(size(y)); errorbar(x,y,error, 'horizontal' ) |
Output:
MATLAB allows us to print both vertical and horizontal error bars together, of the same length.
Example 3:
Matlab
x = 0.1*[1:2:23]; %xdata y = x.^2; %ydata error = 0.23*ones(size(y)); %defining error bars of same length errorbar(x,y,error, 'both' ) |
Output:
We can have variable lengths of error bars on either side of the y curve. See the following implementation for the same.
Example 4:
Matlab
x = [1 3 5.5 6 6.9 7.5 7.9]; %xdata y = 0.003*x.^3; %ydata %defining error bars above the curve error_pos = [1 0.5 1 0.2 0.3 0.23 0.7]; %defining error bars above the curve error_neg = [0.7 0.23 0.3 0.2 1 0.5 1]; % first we pass the error below curve % then, error above curve errorbar(x,y,error_neg,error_pos) |
Output:
We can plot both vertical and horizontal error bars of variable lengths.
Example 5:
Matlab
x = [1 3 5.5 6 6.9 7.5 7.9]; %xdata y = 0.003*x.^3; %ydata y_error_pos = [1 0.5 1 0.2 0.3 0.23 0.7]; %defining y-error bars above the curve y_error_neg = [0.7 0.23 0.3 0.2 1 0.5 1]; %defining y-error bars below the curve x_error_pos = [0.7 0.23 0.3 0.2 1 0.5 1]; %defining x-error bars above the curve x_error_neg = [1 0.5 1 0.2 0.3 0.23 0.7]; %defining x-error bars below the curve %first the errors along y-axis are passed in order and then, that of x-axis errorbar(x,y,y_error_neg,y_error_pos,x_error_neg,x_error_pos, 'o' ) |
Output:
The ‘o’ option plots a circle at (x, y) point instead of a continuous line.
We can also get the properties of the error bar created by making it an object like below:
Example 6:
Matlab
x = [1 3 5.5 6 6.9 7.5 7.9]; %xdata y = 0.003*x.^3; %ydata %defining y-error bars above the curve y_error_pos = [1 0.5 1 0.2 0.3 0.23 0.7]; %defining y-error bars below the curve y_error_neg = [0.7 0.23 0.3 0.2 1 0.5 1]; %defining x-error bars above the curve x_error_pos = [0.7 0.23 0.3 0.2 1 0.5 1]; x_error_neg = [1 0.5 1 0.2 0.3 0.23 0.7]; err = errorbar(x,y,y_error_neg,y_error_pos,x_error_neg,x_error_pos, 'o' ) %creating an errorbar object |
Output:
The plot would be:
And the properties will be displayed in the terminal.