MATLAB Answers

When using yyaxis is there a way to plot the right yaxis data behind the left yaxis data?

62 views (last 30 days)
Heidi Hirsh
Heidi Hirsh on 3 Apr 2020
Edited: Tommy on 26 May 2020
I am trying to plot data on two different axes. I want the data associated with the right y axis (red lines) to plot behind the data points associated with the left y axis. Right now the right axis data is plotting in the front even though I run those lines first. Is there a way to fix this? I don't want to change the y axes (pH makes more sense on the right). Thank you for any advice!
This is how I am plotting now:
figure
yyaxis right
hold on
box on
plot(MX,PH2_1d,'-','color','r','linewidth',3)
plot(MX,poPH3_1d,':','color','r','linewidth',3)
ylim([7.85 8.35])
ylabel('pH')
yyaxis left
hold on
plot(MX,flo_ugL,'.','Color',[.6 .6 .6],'markersize',1)
errorbar(n_sdn,nflo_mean,nflo_std,'.','markersize',22,'color',[0 .4 .4],'capsize',0,'linewidth',1)
plot(date_nf_off,fronds2,'.','markersize',49,'Color','k')
ylabel('[Chlorophyll-a]')
ylim([0 30])
x = datenum('June-27-2018'):7:datenum('Oct-3-2018');
set(gca, 'XTick', x);
datetick('x','mm/dd','keepticks');
ax=gca; % make y axes black
ax.YAxis(1).Color='k'
ax.YAxis(2).Color='k'
set(gca,'fontsize',font)

Answers (1)

Tommy
Tommy on 4 Apr 2020
Edited: Tommy on 26 May 2020
Normally uistack would work, but see here:
You might alternatively consider plotting your data on two separate axes, with the top axes transparent ('Color' set to 'none'):
f = figure;
ax1 = axes(f, 'NextPlot', 'add', 'YAxisLocation', 'right', 'Box', 'on');
p1 = plot(ax1, 1:100, 10*rand(100,1),'-','color','r','linewidth',3) ;
p2 = plot(ax1, 1:100, 10*rand(100,1),':','color','r','linewidth',3);
ylabel(ax1, 'more random numbers')
xlabel(ax1, 'index')
ax2 = axes(f, 'NextPlot', 'add', 'Color', 'none');
plot(ax2, 1:100, rand(100,1),'.','Color',[.6 .6 .6],'markersize',1)
plot(ax2, 1:100, rand(100,1),'.','markersize',49,'Color','k')
set(ax2, 'XTick', []);
set(ax2, 'XTickLabel', []);
ylabel(ax2, 'random numbers')
('NextPlot' set to 'add' acts like hold on and prevents properties such as YAxisLocation from being reset when you call plot).

Community Treasure Hunt

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

Start Hunting!