Plotting Error Bars in MATLAB
Last Updated :
04 Nov, 2022
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
x = 0.1*[1:35];
y = x.^2;
error = 3*ones(size(y));
errorbar(x,y,error)
|
Output:
We can change the error bars from vertical to horizontal.
Example 2:
Matlab
x = 1:2:23;
y = x.^2;
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];
y = x.^2;
error = 0.23*ones(size(y));
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];
y = 0.003*x.^3;
error_pos = [1 0.5 1 0.2 0.3 0.23 0.7];
error_neg = [0.7 0.23 0.3 0.2 1 0.5 1];
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];
y = 0.003*x.^3;
y_error_pos = [1 0.5 1 0.2 0.3 0.23 0.7];
y_error_neg = [0.7 0.23 0.3 0.2 1 0.5 1];
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];
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];
y = 0.003*x.^3;
y_error_pos = [1 0.5 1 0.2 0.3 0.23 0.7];
y_error_neg = [0.7 0.23 0.3 0.2 1 0.5 1];
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' )
|
Output:
The plot would be:
And the properties will be displayed in the terminal.
Share your thoughts in the comments
Please Login to comment...