I'm trying to call patch without permanently changing my X axis from a datetime array.

Hi. I'm trying to call patch without permanently changing my X axis from a datetime array. Here is an example of what I'm trying to do. The call to temporarily change the data type in XData is not working. Any suggestions?
% Create data & plot
x = datetime(2017,1,1) + caldays(1:31);
y = rand(1,31);
plt = plot(x, y);
% Convert X axis to a double
plt.XData = datenum(plt.XData);
% Shade patch area
Ys = ylim;
Y1 = [Ys(1),Ys(2),Ys(2),Ys(1)];
x1 = datenum(datetime(2017,1,14));
x2 = datenum(datetime(2017,1,21));
ptch = patch([x1 x1 x2 x2], Y1, [0 0 0]);
ptch.FaceAlpha = .15;
% Convert X axis back to a datetime type
plt.XData = datetime(plt.XData, 'ConvertFrom', 'datenum');

 採用された回答

Walter Roberson
Walter Roberson 2017 年 10 月 9 日
編集済み: Walter Roberson 2020 年 5 月 15 日
x = datetime(2017,1,1) + caldays(1:31);
y = rand(1,31);
plt = plot(x, y);
hold on
x1 = datetime(2017,1,14);
x2 = datetime(2017,1,21);
fx = [x1 x2 x2 x1 x1]
Ys = ylim;
fy = [Ys(1) Ys(1) Ys(2) Ys(2) Ys(1)];
fill( fx, fy, [0 0 0], 'FaceAlpha', 0.15);
hold off

4 件のコメント

Bill
Bill 2017 年 10 月 9 日
Thanks!
I get this error in R2019b,
Error using datetime/horzcat (line 1335)
All inputs must be datetimes or date/time character vectors or date/time
strings.
Walter Roberson
Walter Roberson 2020 年 5 月 15 日
Please show your call to datetime() that is triggering the problem, including showing the class() of each of the variables you are passing in.
Jonas Bauer
Jonas Bauer 2022 年 6 月 9 日
Works perfectly!

サインインしてコメントする。

その他の回答 (1 件)

Sean de Wolski
Sean de Wolski 2017 年 10 月 9 日
Use fill instead of patch.
% Create data & plot
x = datetime(2017,1,1) + caldays(1:31);
y = rand(1,31);
plt = plot(x, y);
% Convert X axis to a double
% plt.XData = datenum(plt.XData);
% Shade patch area
Ys = ylim;
Y1 = [Ys(1),Ys(2),Ys(2),Ys(1)];
x1 = (datetime(2017,1,14));
x2 = (datetime(2017,1,21));
ptch = fill([x1 x1 x2 x2], Y1, [0 0 0]);
ptch.FaceAlpha = .15;

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

製品

タグ

質問済み:

2017 年 10 月 9 日

コメント済み:

2022 年 6 月 9 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by