How do I draw a colored rectangle on a graph when the x-axis is equal to time?

I want to draw a background rectangle behind some data. Rectangle

does not support tenses as x coordinates or widths. Is there any other way to do this?

Simple case:

time_data = datetime(2017,7,23) + duration(6,0:10:(60*14),0);
data = sort(rand(size(time_data)));
time_rectangle = datetime(2017,7,23) + duration([9 5+12],0,0);

figure(1)
plot(time_data,data)
hold on
plot([time_rectangle(1) time_rectangle(1)],ylim(),'--k','linewidth',1)
plot([time_rectangle(2) time_rectangle(2)],ylim(),'--k','linewidth',1)

ylimits = ylim();
rectangle(time_rectangle(1),ylimits(1),diff(time_rectangle),diff(ylimits))

      

(if rectangle worked, the rectangle would be in front of the data, but that would be easy to fix)

+3


source to share


1 answer


You can use different axes for this. Instead of the last line above, enter the following:

xlimits = xlim(); % get the time limits
num_rectangle = datenum(time_rectangle); % convert the rectangle unites to numeric
axes; % add another axes
% add the rectangle only with numeric units:
rectangle('Position',... % draw a semi-transparent green rectangle
          [num_rectangle(1) ylimits(1) diff(num_rectangle) diff(ylimits)],...
          'FaceColor',[0.5 1 0.5 0.5],'EdgeColor','none')
xlim(datenum(xlimits)) % set the new axes limits to be the same as the the original axes
axis off % turn off the new axes, to see the only the rectangle

      



rectangle

+1


source







All Articles