簡體   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