繁体   English   中英

当 x 轴是时间时,如何在绘图上绘制彩色矩形?

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

我想在一些数据后面绘制一个背景矩形。 Rectangle不支持时间作为 x 坐标或宽度。 有没有其他方法可以做到这一点?

简单案例:

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))

(如果矩形有效,矩形将位于数据前面,但这很容易修复)

您可以为此使用不同的轴。 输入以下内容,而不是上面的最后一行:

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

矩形

在 R2020b 和可能更早的版本中,“填充”命令可用于绘制任意形状,包括矩形,其中 x 轴由日期组成。 这篇文章包含您需要的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM