# How to set the number of x-axis ticks on a datetime plot?

조회 수: 36(최근 30일)
K E 2016년 11월 15일
댓글: Théo Gonin 2021년 5월 31일 9:28
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 2016년 11월 15일
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.
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Théo Gonin 2021년 5월 31일 9:28
You say :
"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"
Would you kindly explain how to do that ?
I'm interested too @Peter Perkins.

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!

Translated by