Filter löschen
Filter löschen

Problem with x-axis and dates in plot

4 Ansichten (letzte 30 Tage)
Christian F.
Christian F. am 7 Nov. 2013
Kommentiert: Kelly Kearney am 8 Nov. 2013
Hi everybody,
I want to plot 228 datapoints, which correspond to monthly observations from 01/1993 to 12/2011.
The x-axis of the plot should be in 'yyyy' format, showing the first year (1993), the last year (2011) and maybe three or four equally spaced dates in between those years.
How can I do that?
Thanks in advance, Chris

Antworten (2)

Kelly Kearney
Kelly Kearney am 7 Nov. 2013
If you're not too picky about exactly which years are labeled, datetick should do it. Assuming t holds your time data (as datenumbers):
y = rand(228,1);
[month, yr] = ndgrid(1:12, 1993:2011);
t = datenum(yr(:), month(:), ones(numel(yr),1));
plot(t,y);
datetick('x', 'yyyy');
If you want to be more specific about exactly which years are labeled, set the xticks manually before calling datetick, and then use the 'keepticks' and 'keeplimits' options.

Christian F.
Christian F. am 8 Nov. 2013
Thanks a lot Kelly!
Your answer works almost perfectly. One remaining problem is that matlab shows the x axis from 1990 - 2020, so there is some free space to the left and to the right. I tried to set limits for the x axis but it didn't work.
Best, Chris
  1 Kommentar
Kelly Kearney
Kelly Kearney am 8 Nov. 2013
So set your preferred axis limits, and then use 'keeplimits' to make datetick respect this:
y = rand(228,1);
[month, yr] = ndgrid(1:12, 1993:2011);
t = datenum(yr(:), month(:), ones(numel(yr),1));
plot(t,y);
set(gca, 'xlim', [min(t) max(t)]);
datetick('x', 'yyyy', 'keeplimits');

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Line Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by