MATLAB: Do the x-tick labels overlap when I update them in a plot created using PLOTYY

axesdwhhgwaitlabelsMATLABoverlapoverwriteplotyytickx-tick

When I use PLOTYY to generate a figure, a subsequent change to the x-tick labels causes the new x-tick labels to overlap the old ones.
The following code demonstrates this behavior:
x=[1:10]
y1=2*x;
y2=3*x;
plotyy(x, y1, x, y2)
datetick('x',2) % modify the x-tick labels

Best Answer

Using PLOTYY creates two overlapping X-Axes along with the desired set of Y-Axes.
Subsequently changing the x-tick labels using DATETICK or set(gca, ‘XTickLabel’, …) only changes the x-tick labels of one of these two x-axes resulting in the overlap.
In order to work around this issue, you can delete the tick labels from both sets of x-axes and then assign new x-tick labels. The following code illustrates this workaround:
x=[1:10]
y1=2*x;
y2=3*x;
plotyy(x, y1, x, y2)
[AX,H1,H2] = plotyy(x, y1, x, y2)
set(AX, 'xTickLabel','') % delete the x-tick labels
datetick('x',2) % update the x-tick labels
In the above code, [AX,H1,H2] = plotyy(...) returns the handles of the two axes created in AX and the handles of the graphics objects from each plot in H1 and H2. AX(1) is the left axes and AX(2) is the right axes.
Alternatively, you can set the dateticks on both axes, as in the example below:
x = datenum(0:0.01:20);
y1 = 200*exp(-0.05*x).*sin(x);
y2 = 0.8*exp(-0.5*x).*sin(10*x);
AX = plotyy(x,y1,x,y2,'plot');
datetick(AX(1),'x',20)
datetick(AX(2),'x',20)
Another option is to link the properties of both axes as shown in the example below:
x=[1:10];
y1=2*x;
y2=3*x;
[AX,H1,H2] = plotyy(x,y1,x,y2,'plot');
linkprop(AX,{'Xlim','XTickLabel','Xtick'}); % Link the limits of both axes, and the labels
axes(AX(2));datetick('x',20) % Now use DATETICK
axis tight