
How to change a section of the background color of plot?
5 views (last 30 days)
Show older comments
Hi!
I have the following two plots:


The "in sight" plot is a binary array with as many elements as the "Elevation" and "Azimuth" arrays. I would like to change the background of the first plot, such that when the "in sight" variable is 0, the background is red, and when the "in sight" variable is 1, the background is green. I would look something like this:

Does anyone know a method to obtain such a figure? Thanks!
EDIT:
I've tried using patch, but that doesn't allow datetime inputs for the x-axis. Not sure how I would overcome that.
1 Comment
Peter P
on 30 Apr 2020
Its an old question, but if anyone needs something similar, I hope this helps.
I had a vector Av which contained ones and zeros and I wanted to color the area that had ones with green, and the area with zeros as red in the background.

I borrowed the idea from Adam and made the following:
j=2;
x(1) = 1;
for i = 1:length(Av(:,1))-1
if(Av(i,1) ~= Av(i+1,1))
x(j) = i; j = j+1;
end
end
i = length(x(1,:));
x(i+1) = length(Av(:,1));
for i = 2:length(x(1,:))
hold on
if(sum(Av(x(1,i-1):x(1,i),1)) <= 1)
y = patch(x([i-1,i,i,i-1]), [0 0 30 30], 'red');
y.FaceAlpha = 0.2; %make face a little transparent
y.EdgeAlpha = 0; %make edge totally transparent
else
y = patch(x([i-1,i,i,i-1]), [0 0 30 30], 'green');
y.FaceAlpha = 0.2; %make face a little transparent
y.EdgeAlpha = 0; %make edge totally transparent
end
end
Answers (1)
Adam Danz
on 2 Jan 2019
Edited: Adam Danz
on 30 Apr 2020
For datetime axes, you can use datenum() and datetick() as in the example below. This allows you to apply a patch object to the axes.
times = {'18:00', '18:30', '19:00', '19:30', '20:00', '20:30'};
dt = datetime(times, 'InputFormat', 'HH:mm', 'format', 'HH:mm'); %datetime format
x = datenum(dt); %numeric format
figure
patch(x([3,4,4,3]), [0 0 1 1], 'red')
xlim([min(x), max(x)])
ylim([0,1])
datetick('x', 'keeplimits') %put axis labels back into datetime
0 Comments
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!