Problem with x-axis and dates in plot

3 views (last 30 days)
Christian F.
Christian F. on 7 Nov 2013
Commented: Kelly Kearney on 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

Answers (2)

Kelly Kearney
Kelly Kearney on 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. on 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 Comment
Kelly Kearney
Kelly Kearney on 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');

Sign in to comment.

Categories

Find more on Line Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!