Effacer les filtres
Effacer les filtres

Problem with x-axis and dates in plot

4 vues (au cours des 30 derniers jours)
Christian F.
Christian F. le 7 Nov 2013
Commenté : Kelly Kearney le 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

Réponses (2)

Kelly Kearney
Kelly Kearney le 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. le 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 commentaire
Kelly Kearney
Kelly Kearney le 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');

Connectez-vous pour commenter.

Catégories

En savoir plus sur Line Plots dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by