1
votes

I am trying to add a grey shaded area between two user-defined vertical lines. I need this gray shaded area to appear beneath my already plotted data. I have tried using the fill and area functions, but haven't been able to successfully create a bounded area to appear underneath the Matlab plot. I need the shaded area plot to extend from the x-axis at vertical lines created at 5.5 and 19 and extend up to the y-axis at 900 (left y-axis) and at 1 (right y-axis). See here: https://www.dropbox.com/s/qyzkuhw17yxn8p5/sample.png

3
Please provide an example and describe better the area that you need to fill (the current description is confusing).randomatlabuser
So I plotted the four y variables first, then tried to use fill function like so: fill([5.5 5.5 19 19], [0 900 900 0], [0.5 0.5 0.5], 'EdgeColor', 'none'). This resulted in the gray shaded area blocking the data as shown here: dropbox.com/s/ltjbhzznfkyh0ds/shade.pnguser3052817
A. Donda and I have given two alternative solutions to that problem.randomatlabuser
@user3052817: Did one of us help you?A. Donda

3 Answers

2
votes

I suppose the problem does not lie in generating the shaded area, but in making it appear below other elements of the plot even though it gets plotted later. You can achieve that by locating it "deeper", i.e. at a smaller z-value. Here is an example, building on the code by randomatlabuser:

x = linspace(0, 24, 100);
plot(x, 450 - 400 * cos(x / 12 * pi), 'k.-')
hold all

x = [5.5 5.5 19 19 5.5];
y = [0 900 900 0 0];
patch(x, y, -1 * ones(size(x)), [0.9 0.9 0.9], 'LineStyle', 'none')

patch is essentially the same as fill, but has a version that supports a third coordinate, the z-value.

1
votes

From what I understand you want to do this:

h1 = plot((0:24), (0:700/24:700), '-b', 'LineWidth', 10); % some function
hold on
h2 = plot((0:24), 1.5 * (0:24) .^2, '-r', 'LineWidth', 10); % some other function

x = [5.5 5.5 19 19 5.5]; y = [0 900 900 0 0]; % define edges of area
h3 = fill(x, y, [0.9 0.9 0.9], 'LineStyle', 'none'); % fill area

set(gca, 'Children', [h1 h2 h3]) % h3 in the background, then h2 and finally h1 upfront

If not, you need to explain better what you are after.

0
votes
    % Add shaded area to plot

    % Line 1
    hl1 = line(x1,y1,'Color','b'); 

    x = [5.5 5.5 19 19]; y = [0 900 900 0]; % define edges of shaded area

    % Locations for 5:30am and 19:00pm with the left y-axis ranging from 0-900 

    hl2=fill([x(1) x(2) x(3) x(4)], [y(1) y(2) y(3) y(4)],'Color','r','EdgeColor','none','LineStyle','none'); 

    hl1 = line(x1,y1,'Color','b'); % Replot line 1 over shaded area
    hold on; 

    % Continue adding more shaded areas using the fill function or add lines directly...