How to format x date axis?

44 次查看(过去 30 天)
Hi
I did try to find a answer online but I didn't get a good one so I am asking here for clearer help.
In my plot (z vs. date) with date(mmm-dd-yyyy) being x axis. I'd like to format x-axis so it start from Jan-01-2008 to Jan-01-2014 with an interval of every 90 days(3 months). I never get correct answers. I am very confusing by the results.
Here are what I did.
1. convert date from excel to datenum, dn_Prod=datenum(CycleDate_Prod,'mm/dd/yyyy');
2. plot the line, hLine=plot(hAx(1),dn_Prod,equivalentheave,'-k','linewidth',2,'DisplayName',legendlabel_equiuplift);
3. format the x-axis
datetick('x','mmm-YYYY','keepticks','keeplimits');
startdatenum=datenum('Jan-01-2008','mmm-dd-yyyy');
enddatenum=datenum('Jan-01-2014','mmm-dd-yyyy');
set(gca,'XTick',[startdatenum:90:enddatenum]);
I think I did correctly, but I never get it right.
Anyone help me find the problem in the above scripts? Thanks a lot.

采纳的回答

Steven Lord
Steven Lord 2018-1-11
If you're using a sufficiently recent release of MATLAB, release R2016b or later, you can call plot with a datetime array as one of the inputs. I recommend doing that instead of calling plot with a vector of serial date numbers generated by datenum. For more information see this example in the documentation.
  2 个评论
roudan
roudan 2018-1-11
Thanks Steven, I found a solution now. datetick() has to be after set() function then it works. don't know why. Thanks
Walter Roberson
Walter Roberson 2018-1-11
datetick() sets the XTickLabels based upon the current tick positions (if 'keepticks' was specified) or based upon the data range (if 'keepticks' was not specified.) datetick() does not modify the properties of the axes to know that date format should be used for all changes to XTick that are made after datetick() is called.
The R2016b+ approach of using datetime() objects does modify the axes properties to know to continue to use date format when XTick are changed.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by