How to draw a colored rectangle on a plot when x-axis is time?

Viewed 2218

I want to draw a background rectangle behind some data. Rectangle does not support times as the x-coordinate or the width. Is there some other way of doing 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)

2 Answers

In R2020b and possibly earlier versions, the "fill" command can be used to draw arbitrary shapes, including rectangles, where the x axis consists of dates. This post contains the info you need.

Related