plotyy: how to use 'datetick' on both axis
9 views (last 30 days)
Show older comments
I used 'plotyy' to plot some data on left and right y-axis. Both the data have xaxis in date format. Therefore, at first, I plotted the y data against date-numbers; then I a using 'datetick' to convert my x-axis ticks to date format. But, it seems that 'datetick' does not allow using axis-objects, so it only converts one of the axis in date format. The other axis is left in date-number format. I am using following code:
figure;
Ax=plotyy(s_xaxis,streamflow,p_xaxis,prcp);
datetick('x','mm/dd/yyyy')
set(Ax(1),'linewidth',2);
set(Ax(2),'Ydir','reverse','xAxisLocation','Top');
Please suggest a way so that both the axis can be converted to date format.
0 Comments
Accepted Answer
Walter Roberson
on 30 Apr 2018
datetick does accept axes handle as the first argument.
datetick(Ax(1), 'x', 'mm/dd/yyyy')
datetick(Ax(2), 'x', 'mm/dd/yyyy')
On the other hand, for plotyy there should only be one visible x axis, so it might just be a matter of selecting the right one.
2 Comments
Walter Roberson
on 30 Apr 2018
For example:
ax = plotyy(1:10,rand(1,10),1:20,10*rand(1,20));
datetick(ax(1), 'x', 'mm/dd')
More Answers (1)
dpb
on 30 Apr 2018
Edited: dpb
on 30 Apr 2018
"It seems that 'datetick' does not allow using axis-objects, ..."
Not so--
>> help datetick
....
datetick(AX,...) uses the specified axes, rather than the current axes.
...
Still, don't use datenum any longer unless you run into a dead end that some particular specialty plot or other function doesn't work with datetime objects instead; much more flexible and the plot routines are now datetime aware and there's the datetimeruler object with it instead of the much more fickle and hard-to-use datetick.
Also, plotyy is deprecated in favor of yyplot altho there I don't fault so much; it just is a slightly different route to the same end.
So, for your case
stime=datetime(s_xaxis,'convertfrom','datenum');
ptime=datetime(p_xaxis,'convertfrom','datenum');
hAx=plotyy(stime,streamflow,ptime,prcp);
What you will also want to do for two axes is to linkaxes the x-axes and I've found it better to turn off ticks for the second as on occasion there's been a bit of jitter and the labels/tick marks don't quite line up identically...
hAx(2).Xtick=[]; % use only one set of visible tick marks
While the above doesn't convert to datetime until ready to plot, I'd really suggest going back to the beginning and using it throughout instead.
See Also
Categories
Find more on Two y-axis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!