plot two time series datasets from different years on the same plot ignoring the year

I want to plot two time series datasets from 2019 and 2020 on the same plot to compare them but I want to ignore the year so they are on top of each other. for this I changed the years to 2000 and plot it both but then the xaxis label is 2000. Also this works ok if no leap years but not a good idea if one of the years is a leap year. I also tried converting the datetime to 'day of year' but then the xaxis is a number and I want to show dates.
is there a way to do this without changing the year?

1 件のコメント

Ihab Abboud
Ihab Abboud 2020 年 10 月 30 日
in desperation I dragged the legend to the bottom to cover the year but I don't like workarounds if there is a proper way to do it

回答 (1 件)

Ameer Hamza
Ameer Hamza 2020 年 10 月 30 日
編集済み: Ameer Hamza 2020 年 10 月 30 日
You can run the following lines after creating the figure
ax = gca;
ax.XTickLabelMode = 'manual';
ax.XTickLabel = datestr(ax.XTick,'mmmm dd');

5 件のコメント

Ihab Abboud
Ihab Abboud 2020 年 10 月 30 日
Thanks. This works if you make both years the same but that is dangerous if one of the years is a leap year
Ameer Hamza
Ameer Hamza 2020 年 10 月 30 日
Yes, but that is a general problem, irrespective of the method used to plot. How do you want to compare two years when one of them is a leap year?
Ihab Abboud
Ihab Abboud 2020 年 10 月 30 日
I get it. It is a general problem but if a year has Feb 29 and you take the data and change the year to a non leap year that might create an issue. I just was hopping there is a way of doing this without making both years the same year then plotting. It works with day number (or day of year) but then I don't like the axis labels. I guess I can always change the label on the axis to whatever I want but I like automations
Ihab Abboud
Ihab Abboud 2020 年 10 月 30 日
thanks you for your help by the way I used the above the code
You can do something like this so that you don't need to change the year number
t1 = datetime(2019,1,1):datetime(2019,12,31);
y1 = rand(size(t1));
t2 = datetime(2020,1,1):datetime(2020,12,31);
y2 = rand(size(t2));
ax1 = axes();
hold(ax1);
plot(t1, y1);
ax1.XTickLabelMode = 'manual';
ax1.XTickLabel = datestr(ax1.XTick,'mmm dd');
ax2 = axes('Position', ax1.Position, 'Visible', 'off');
hold(ax2);
plot(t2, y2, 'r')
However, note that in this case, the difference will be offset by 1 day. A reasonable approach seems to remove the extra day.

この質問は閉じられています。

製品

リリース

R2019b

質問済み:

2020 年 10 月 30 日

閉鎖済み:

2021 年 8 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by