Two y-Axes plot order and legend issue

70 views (last 30 days)
Cakil
Cakil on 10 Apr 2024 at 12:44
Commented: Cakil on 11 Apr 2024 at 7:52
Hello Matlab Community,
I am having problems on 2 y-axes plot. Here are the issues:
  • I try to plot Two y-Axes plot with the output of yyaxis right is back and yyaxis left is front. I have tried set(gca, 'SortMethod', 'depth') but it looks like it did not change anything.
  • Another issue is the legend colors. "P" supposed to be grey line but somehow it starts from green.
  • I want to export the high resolution png figure with exportgraphics but whenever I try to use it, my MATLAB freezes and quits responding. Unfortunately I did not even have chance to get the error code.
I will appreciate your help regarding these issues.
load('data1.mat')
load('data2.mat')
load('data3.mat')
clf
yyaxis right
plot(D.Time, D.Quantumumolm2s,Color=[0.8 0.8 0.8], LineWidth=1)
ylabel('P')
yyaxis left
hold on
line(Gk_tt.Time(1:15),Gk_tt{1:15,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",14,LineStyle="-")
hold on
line(Rk_tt.Time(1:15),Rk_tt{1:15,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",14,LineStyle="-")
hold on
stem(NK.Time(1:15),Nk_cal1(1:15,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",14,LineStyle="-")
hold on
line(GM.Time,GM{:,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",16,LineStyle="-")
hold on
line(RM.Time,RM{:,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",16,LineStyle="-")
hold on
stem(RM.Time,NM(:,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",16,LineStyle="-")
xlabel('Time')
ylabel('GK,RK and NK')
ax = gca;
ax.YAxis(1).Color = 'k';
ax.YAxis(2).Color = 'k';
tMark = datetime(2019,5,5); % Time to mark by a vertical line
text(tMark + days(0.5), mean(ylim)*2 , {'Start', 'layer'}, 'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'left', 'FontSize', 14, 'Color', 'blue');
plot([tMark tMark], ylim,"Color","b",LineWidth=1,LineStyle="-");
legend('P','GK','RK','NK','','','',Location='northwest')
datetick
xlim([datetime('April 20, 2019'), datetime('June 5, 2019')])
fontsize(gca,16,"points")
set(gca, 'SortMethod', 'depth')
set(gcf, 'WindowState', 'maximized')
exportgraphics(gca,"m.png",'Resolution',600)

Accepted Answer

Voss
Voss on 10 Apr 2024 at 14:46
Edited: Voss on 10 Apr 2024 at 14:58
  1. With yyaxis, I don't think there is a way to set which axes' lines show up in front of the other. However, a workaround is to create two separate axes and coordinate their positions and x-limits using linkprop/linkaxes. See below. Since the right axes is created first, its lines show up under the left axes' lines.
  2. Store the line handles when the lines are plotted, and specify which handles to include in the legend in the legend call. See below.
  3. I don't know why MATLAB freezes with exportgraphics. If you use the workaround in #1, you'll have two axes, and to get them both in one exported image, you'll have to export the figure. See below. Maybe that will avoid the freezing. Try it and see.
load('data1.mat')
load('data2.mat')
load('data3.mat')
clf
ax_right = axes();
hP = plot(D.Time, D.Quantumumolm2s,Color=[0.8 0.8 0.8], LineWidth=1);
ylabel('P')
ax_right.YAxisLocation = 'right';
ax_right.XTick = [];
ax_left = axes('Color','none');
hold on
hG = line(Gk_tt.Time(1:15),Gk_tt{1:15,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",14,LineStyle="-");
hR = line(Rk_tt.Time(1:15),Rk_tt{1:15,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",14,LineStyle="-");
hN = stem(NK.Time(1:15),Nk_cal1(1:15,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",14,LineStyle="-");
line(GM.Time,GM{:,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",16,LineStyle="-")
line(RM.Time,RM{:,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",16,LineStyle="-")
stem(RM.Time,NM(:,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",16,LineStyle="-")
xlabel('Time')
ylabel('GK,RK and NK')
ax_left.YAxis.Color = 'k';
ax_right.YAxis.Color = 'k';
legend([hP,hG,hR,hN],{'P','GK','RK','NK'},Location='northwest')
datetick
fontsize([ax_left ax_right],16,"points")
linkprop([ax_left ax_right],'Position');
linkaxes([ax_left ax_right],'x')
xlim([datetime('April 20, 2019'), datetime('June 5, 2019')])
yl = ylim(ax_left);
tMark = datetime(2019,5,5); % Time to mark by a vertical line
text(tMark + days(0.5), mean(yl)*2 , {'Start', 'layer'}, 'VerticalAlignment', 'bottom', 'HorizontalAlignment', 'left', 'FontSize', 14, 'Color', 'blue');
plot([tMark tMark], yl,"Color","b",LineWidth=1,LineStyle="-");
set(gcf, 'WindowState', 'maximized')
exportgraphics(gcf(),"m.png",'Resolution',600)
  2 Comments
Cakil
Cakil on 10 Apr 2024 at 21:13
Dear @Voss, thank you very much for your answer.
It is a very nice alternative to create what I aimed to do, I will definitely keep "linkprop/linkaxes" options in my mind for such cases.
Matlab is also able to export the figure without quitting responding.
Voss
Voss on 10 Apr 2024 at 21:23
You're welcome!
"Matlab is also able to export the figure without quitting responding."
Good to hear! I've seen others have problems using exportgraphics with yyaxis, for example, in this question. In that particular case plotyy seemed to work where yyaxis did not. That's something to keep in mind in case you run into any other problems exporting.

Sign in to comment.

More Answers (1)

Cris LaPierre
Cris LaPierre on 10 Apr 2024 at 14:33
Edited: Cris LaPierre on 10 Apr 2024 at 14:34
1. What ever is plotted later is in front. The simplest approach is to change the order you plot the lines. If you want the gray lines to be in front, plot it last.
2. Try calling legend without any inputs to see what the order of your line objects are. The gray line is last in the list, as it appears the lines in the left axis are added first. You can manually update this by specifying the object order in legend (see this example). You'll need to capture the line objects first, which I have done below.
3. I haven't looked into exproting the graphic.
Note that I've made some other small updates to your code (only need to call 'hold on' once. Should be paired with a 'hold off'. Use xline to create a vertical ilne).
load('data1.mat')
load('data2.mat')
load('data3.mat')
yyaxis left
GK = line(Gk_tt.Time(1:15),Gk_tt{1:15,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",14,LineStyle="-");
hold on
RK = line(Rk_tt.Time(1:15),Rk_tt{1:15,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",14,LineStyle="-");
NK = stem(NK.Time(1:15),Nk_cal1(1:15,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",14,LineStyle="-");
line(GM.Time,GM{:,1},"LineWidth",1,"Color",[0, 0.5, 0],"Marker",".","MarkerSize",16,LineStyle="-")
line(RM.Time,RM{:,1},"LineWidth",1,"Color",[0.6350, 0.0780, 0.1840],"Marker",".","MarkerSize",16,LineStyle="-")
stem(RM.Time,NM(:,1),"LineWidth",1,"Color",[0.9290 0.6940 0.1250],"Marker",".","MarkerSize",16,LineStyle="-")
hold off
xlabel('Time')
ylabel('GK,RK and NK')
yyaxis right
P = plot(D.Time, D.Quantumumolm2s,Color=[0.8 0.8 0.8], LineWidth=1);
ylabel('P')
ax = gca;
ax.YAxis(1).Color = 'k';
ax.YAxis(2).Color = 'k';
tMark = datetime(2019,5,5); % Time to mark by a vertical line
xline(tMark,'-b',{'Start', 'layer'},LineWidth=1,LabelOrientation='horizontal',FontSize=14)
legend([P GK RK NK],'P','GK','RK','NK',Location='northwest')
datetick
xlim([datetime('April 20, 2019'), datetime('June 5, 2019')])
fontsize(gca,16,"points")
  3 Comments
Cris LaPierre
Cris LaPierre on 10 Apr 2024 at 21:25
The error would suggest the value you are using for tMark does not match the data type of your x axis.
Running the code I shared, I am not able to reproduce the error despite running the code in R2022b multiple times. Is there anything in particular you need to do to get the error to appear?
Cakil
Cakil on 11 Apr 2024 at 7:52
I just copied the code and run it, that is all.
For some reason, I have never had chance to use xline, it is always the same error whenever I use. I am pretty sure it is not specific for this code but something else.

Sign in to comment.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!