How to set the number of x-axis ticks on a datetime plot?
40 views (last 30 days)
If I plot a variable y at times given by a datetime vector t, the x-axis ticks are automatically chosen,
t = [datetime('now'):1/12:datetime('tomorrow')]; % Example datetime vector
y = rand(size(t)); % Some time dependent variable to plot
plot(t, y); % x-axis ticks every 2 hours
How can I specify the number of ticks, as is done in the very useful program axdate? I don't want to say "make ticks every xx minutes", instead I would like to say "make about 20 xticks" because while I don't always know the tick interval I want, I may know 20 tick labels are easy to read. I say "about 5 ticks" because I would like the resulting tick spacing to be some human-readable interval, such as 1 minute instead of 53 seconds, like in axdate.
Peter Perkins on 15 Nov 2016
Plotting with datetime automatically chooses what it thinks is an appropriate tick label format, based on the time span of the axis. It also chooses what it thinks will be a readable number of ticks, based on the size of the figure window, the font size, and the format. It sounds like you would prefer a different choice. (I would think 20 ticks and labels would be way too many, but that may just have been an example.)
There's not currently a way to say "about 20 ticks". You can let the default behavior happen, or you can set your own tick locations and labels after making the figure (exactly how to set them depends on what version of MATLAB you're using, R2016b has much more seamless and widely supported date/time plotting than did R2014b-R2016a).
As you may already have discovered, choosing "nice looking" ticks in full generality is a difficult bit of code to write. You may find it possible to get the automatically chosen ticks and, say, double their number by putting a new one at each halfway point.
Hope this helps.