0
votes

I have created an example scatter plot with five points in MATLAB as follows:

x = linspace(0,pi,5);
y = cos(x);
scatter(x,y);

In my case, the y-value of each point shall be in a predefined range defined as follows:

y_limits = {[0.9 1.1], [0.6 0.8], [-0.1 0.1], [-0.8 -0.6], [-1.1 -0.9]};

So for example, the y value of point 1 at x = 0 shall be in the range [0.9 1.1].

I would somehow like to draw five vertical boundaries nicely in the same plot perhaps by means of

  • five vertical lines with endpoints at the respective two limits
  • five filled vertical areas between the respective two limits
  • something else that may be more appropriate

I would like to get some suggestions or sample code of people who are more experienced than me in such kind of graphical representations.

2
I'm slightly confused as the y value at x=0 is y=cos(0)=1, so definitely not in the range [0.1, 0.2]? - Wolfie
@Wolfie You are right. I just wanted to provide some example data without caring about mathematical correctness. I have adapted the ranges. - Rickson

2 Answers

2
votes

You can do this in one line by using the errorbar function

% Your example variables
x = linspace(0,pi,5)';
y = cos(x);
y_limits = [0.9, 1.1; 0.6, 0.8; -0.1, 0.1; -0.8, -0.6; -1.1, -0.9];

% Plot
errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'x');
% Format: (x, y, negative error, positive error, point style)

Result:

error bars


Edit, you can set the line properties of the plot as you call errorbar. For example, you could use larger, blue circle markers with thicker, red error bars using:

errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'o', 'MarkerSize', 2, 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'b', 'Color', 'r', 'LineWidth', 1);

Note for these images I'm using grid on to add the grid. Second result:

result 2

1
votes

Creating a lines is done with the line command.

for i = 1:length(x)
line([x(i) x(i)], [y_limits{i}]);
end

Filled areas can be done with patch or fill. Some reordering of the limits is necessary so that the order given follows a path around the area to be filled. One nice trick is to use the alpha command on those filled areas to create transparency.

hold on    
y_corners = reshape([y_limits{:}], 2, length(x)).'; %make an array
y_corners = [y_corners(:,1); flipud(y_corners(:,2))]; %corners follow a path around the shape
fill([x fliplr(x)], y_corners, 'blue');
alpha(0.5);