MATLAB Answers


Draw stack order for yyaxis

Asked by Charles Brown on 20 Apr 2016
Latest activity Commented on by Adam Danz
on 14 Nov 2019 at 12:33
Hello, I'm trying to create an overlaid bar plot using yyaxis. I cannot figure out how to change the stacking order of the two axis objects (and their constituents). The default behavior seems to be that the right yyaxis and its children are above the left yyaxis. Due to the content of my plot, I'd prefer the opposite.
For example, the following script generates two bar plots that are overlaid. One is taller and wider and I'd like it to appear in the background but with its axis on the right side.
backgroundData = [100 75 80 150];
foregroundData = [10 30 25 64];
yyaxis left
ylabel('Foreground Axis')
yyaxis right
ylabel('Background Axis')
I've experimented with uistack, but can't get anything to stick. Of course swapping the left and right axes fixes the issue but I'd rather not do that. Thanks for any insight you can provide.


Sign in to comment.

2 Answers

Answer by Charles Brown on 20 Apr 2016
 Accepted Answer

I have created a work-around using manually-created axes:
backgroundData = [100 75 80 150];
foregroundData = [10 30 25 64];
% This works because ax1 is created AFTER ax2!
ax2 = axes('Position',[0.1300 0.1100 0.7750 0.8150]);
ax1 = axes('Position',[0.1300 0.1100 0.7750 0.8150]);
% Plotting the two bars on their axes. The order here doesn't matter.
% Need to move the Y-axis after plotting the foreground data for some
% reason.
ax2.YAxisLocation = 'right';
ylabel(ax2,'Background Axis')
ylabel(ax1,'Foreground Axis')
% Now we have to set the background of the front axis to be transparent.
set(gca, 'Color', 'None')

  1 Comment

Adam Danz
on 14 Nov 2019 at 12:33
Just use the outdated plotyy() instead. It's a lot cleaner and simpler than overlaying and linking two axes on your own.
Here's a demo:

Sign in to comment.

Answer by Mike Garrity
on 20 Apr 2016

I'm afraid that feature didn't make it into this initial release of yyaxis. As you've noted, the contents of the right side are always on top of the contents of the left side.
I'd be interested in knowing where you first looked when you were trying to figure out how to switch it. , because we've been trying to figure out what the most natural API would be for this.


Most of my thoughts have already been captured by others above (over 2 years!?), so I'd just like to add my request to the pile - having to use a workaround for this is disappointing.
on 5 Nov 2018
please enable uistack to allow my yyaxis right curves to be in the background

Sign in to comment.