Stretching a rectangle over a date axis
Show older comments
Hello, I have a graph with dates as X axis (datetime variables) I'm trying to stretch a rectangle over certain dates (I have the dates stored in a vector), but the problem is that the X axis is datetime and the Y axis is doubles, so MATLAB throws an error. How can I fix this?
for I = 1:1:length(main_idleDateMat(:,1))
startX = main_idleDateMat(I,1);
endX = main_idleDateMat(I,2);
rectangle('Position', [startX idleVecStartHeights(I)-80 (endX - startX) 160]);
end
Accepted Answer
More Answers (3)
There's a nice solution to drawing a semi-transparent colored rectangle over a plot at https://stackoverflow.com/questions/45266078/how-to-draw-a-colored-rectangle-on-a-plot-when-x-axis-is-time
Alternately, you can use area(...) ,setting 'basevalue' to define the bottom of the rectangle:
area([dates(1),dates(2)],[.4,.4],'facecolor',[.8,1,.8], ...
'facealpha',.5,'edgecolor','none', 'basevalue',-.2);
will draw a rectangle with x values between dates(1) and dates(2), and y values between -.2 (basevalue) and .4 .
1 Comment
F S
on 17 Sep 2020
awewome, thanks!
"How can I fix this?"
Use RULER2NUM, which converts from the ruler values (e.g. DATETIME) to numeric, correctly accounting for the ruler starting value:
ax = axes();
t = datetime(2015,1,1:10);
y = [0.2,0.3,0.5,0.2,0.8,0.2,0.3,0.1,0.3,0.4];
plot(ax, t,y,'-o')
x = ruler2num(t,ax.XAxis);
rectangle(ax, 'Position',[x(4),y(4),diff(x(4:5)),diff(y(4:5))], 'Curvature',[0.5,0.6])
Do not use DATENUM or other deprecated functions:

In case somebody still wants to use rectangle, it seems rectangle considers the origin as the low axis limit and the width in number of days (as datetime goes). Thus you have to work with your (rectangle) coordinates as difference from the low time axis limit. I tried plotting a month of data with the time being on x-axis and this works (at least for me):
% Defines dummy time series and plots
time = datetime( [2025 5 3] ) : 1/24 : datetime( [2025 5 28] );
data = rand( size( time ) );
plot( time, data, '.' ); XLim = xlim;
% Draws rectangle from May 15 to May 20 and 0.1 to 0.9
TimPos = datenum( diff( [ XLim(1) datetime( [2025 5 15; 2025 5 20] )' ] ) );
rectangle( 'Position', [ TimPos(1) 0.1 TimPos(2) 0.8 ] )
Be carefull: if you resize using zoom and want to redraw a rectangle, it is the original axis size that works (do not redo an xlim after zooming to determine the new TimPos).
Categories
Find more on Dates and Time 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!
