How to fix non-alignment issue when plotting multiple axes

11 views (last 30 days)
I've produced a plot with 3 y-axes (for y1,y2,y3) using the code given here. x-axis is a datetime axis ranging from 2002 to 2017. I end up with a graph that has an issue with the horizontal alignment of the grids. i.e. x-axis values are not coincided. Highly appreciate any suggestion to fix this issue. The resulting graph is attached for reference. (Release: R2020b)
-Thank you-
%reshape 4D arrays to 2D arrays
y1=reshape(A,1,192);
y2=reshape(B,1,192);
y3=reshape(C,1,192);
%set x axis
x=datetime(2002,1:(16*12),1,'Format','MMM-yyyy');
%plot y1,y2
figure
ax1=axes;
yyaxis left;
y1plot=plot(x,y1,'color',[0.8500,0.3250,0.0980]); %y1 on left
ax1.YColor=[0.8500,0.3250,0.0980];
ylabel('y1');
ax1.XTickMode='manual';
ax1.YTickMode='manual';
ax1.YLim=[min(ax1.YTick), max(ax1.YTick)];
ax1.XLimMode='manual';
grid(ax1,'on')
ytick=ax1.YTick;
yyaxis right
y2plot=plot(x,y2,'-b'); %y2 on right
ax1.YColor='b';
ylabel('y2');
%create 2nd transparent axes & plot y3
ax2 = axes('position',ax1.Position);
y3plot=plot(ax2,x,y3,'-k'); %y3 on left
ylabel('y3');
ax2.Color='none';
grid(ax2,'on');
ax2.YAxis.TickLabelFormat='%.2f';
%horizontally scale the y axis to align the grid
ax2.XLim=ax1.XLim;
ax2.XTick=ax1.XTick;
ax2.YLimMode='manual';
y1=ax2.YLim;
ax2.YTick=linspace(y1(1),y1(2),length(ytick));
%horzontally offset y tick labels
ax2.YTickLabel=strcat(ax2.YTickLabel,{' '});

Accepted Answer

Voss
Voss on 12 Dec 2022
Edited: Voss on 12 Dec 2022
Add the following line at the end of your code:
ax1.Position = ax2.Position;
That seems to fix the problem, but I'm not 100% sure why. Apparently, even though you already had ax2.Position set equal to ax1.Position, ax1's PositionMode (an undocumented axes property I just discovered in trying to answer this question) remained on 'auto', which means that ax1.Position can change, e.g., when the figure's size changes. (ax2.PositionMode is 'manual' because its Position is specified when it is created.) Setting ax1.Position = ax2.Position has the side-effect of setting ax1.PositionMode to 'manual', but, puzzingly, just setting ax1.PositionMode = 'manual' doesn't fix the problem; you have to set ax1.Position = ax2.Position. (Using R2016b.)
  4 Comments

Sign in to comment.

More Answers (1)

Peter Perkins
Peter Perkins on 12 Dec 2022
Dinuka, if that's the plot you are looking for, I guess Voss' suggestion gets you there. But I might also add:
y1=0.45 + .3*rand(192,1);
y2=-0.05 + .2*rand(192,1);
y3=0.3 + .4*rand(192,1);
t=datetime(2002,1:(16*12),1,Format='MMM-yyyy');
tt = timetable(y1,y2,y3,RowTimes=t);
stackedplot(tt)

Community Treasure Hunt

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

Start Hunting!