2nd plot on axes with different x-axis not working

Hi, Im trying to add 2nd plot to an axes using what I've found online. I understand it needs to be axes and not uiaxes.
So I create my first plot from a pushbutton callback
figure
ax=axes;
app.myfigaxes=ax; % assign to app property so I can recall later
plot(ax,X,Y,'LineWidth',2,'Marker','.','MarkerSize',14); grid on;
drawnow;
I have an app property called "myfigaxes"
Now behind a second pushbutton callback I want to add the 2nd plot (but it has different x-axis)
%Create 2nd "Transparent Axes"
ax=app.myfigaxes;
hax2=axes('Position',ax.Position, 'XAxisLocation','top','YAxisLocation','right','Color','none','XColor','r','YColor','r')
hold(ax,"on"); % ax.NextPlot='add';
plot(hax2,X2,Y2,'r-','Marker','.','MarkerSize',14);
xlabel(hax2,'Second X-axis');
linkaxes([ax,hax2],'y');
But my 2nd plot is over the top of the 1st and not transparent, and the XAxislocation is at the bottom not the top as i have required.
where have I gone wrong? (the blue arrow points to a datapoint just about visible from the 1st plot)

 Accepted Answer

dpb
dpb on 19 Feb 2026 at 15:13
Edited: dpb on 19 Feb 2026 at 15:50
hAx(1)=axes;
plot(randn(5,3));
hold(hAx,'on')
hAx(2)=axes('Position',hAx.Position,'XAxisLocation','top', ...
'YAxisLocation','right','Color','none','XColor','r','YColor','r');
hold(hAx(2),'on')
plot(hAx(2),10*rand(1,3),'r-','Marker','.','MarkerSize',14);
Need to set hold on for second axes before calling plot -- it resets the background color otherwise.

More Answers (0)

Categories

Products

Release

R2024b

Asked:

on 19 Feb 2026 at 14:50

Edited:

dpb
on 19 Feb 2026 at 15:50

Community Treasure Hunt

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

Start Hunting!