How can I divide the y-axis of a plot into two different color regions?

16 views (last 30 days)
I am trying to divide a plot into green and red regions orientated horizallay across the y-axis and at a specific point on an eponential curve. For example, I would like the graph background to be green below a value of 5 on the y-axis of a curve and red above that value. Here is what I have tried so far,
y=[1 3 5 7 7.2 7.3 7.5 8 8.5 9];
low=0:5; %I would like the plot background to be green in this range
high=5:10; %I would like the plot background to be red in this range
%function ciplot(lower,upper,x,colour);
% ciplot(lower,upper)
% ciplot(lower,upper,x)
% ciplot(lower,upper,x,colour) % % Plots a shaded region on a graph between specified lower and upper confidence intervals (L and U).
% l and u must be vectors of the same length.
% Uses the 'fill' function, not 'area'. Therefore multiple shaded plots
% can be overlayed without a problem. Make them transparent for total visibility.
% x data can be specified, otherwise plots against index values.
% colour can be specified (eg 'k'). Defaults to blue.
% Raymond Reynolds 24/11/06
%if length(lower)~=length(upper) %error('lower and upper vectors must be same length')
%if nargin<4
%if nargin<3
% x=1:length(lower);
% convert to row vectors so fliplr can work
%if find(size(x)==(max(size(x))))<2
%x=x'; end
%if find(size(lower)==(max(size(lower))))<2
%lower=lower'; end
%if find(size(upper)==(max(size(upper))))<2
%upper=upper'; end
%fill([x fliplr(x)],[upper fliplr(lower)],colour)
%--Error Message--%
%Error using fill
%String argument is an unknown option.
%Error in ciplot (line 36)
%fill([x fliplr(x)],[upper fliplr(lower)],colour)
%Error in example_yaxis_divide (line 21)

Accepted Answer

Geoff Hayes
Geoff Hayes on 27 May 2014
Edited: Geoff Hayes on 27 May 2014
You could try to use the area command to fill in the regions beneath the curve in multiple colours. For example, if your data is
x = -5:0.01:5;
y = exp(x);
you can plot the curve as
Use the find command to determine the last index of y that has a value less than or equal to 5. (In this case, that index is 661.) Then, colour in the area beneath the curve in green for all those y values less than or equal to 5
hold on;
Now colour in the area beneath the curve in red for all those y values greater than 5
In the command window, type help area for more details on this command (and the use of basevalue).
Mark on 28 May 2014
Thanks again, I still couldn't get the find command to work so I just went into the variable browser and found the indices manually, works like a charm now

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!