for plot using 'yyaxis left' and 'yyaxis right' how to add separate legends for the two y axes

31 views (last 30 days)
When using "yyaxis left" and "yyaxis right" for two y-axis plots, how to add legends separately for each y-axis?

Answers (1)

Star Strider
Star Strider on 23 May 2019
The legend is for all the data in the plot (or as many as you want to incllude in the legend call). The y-axis labels are different, and can be specified for each y-axis.
Example —
x = 1:10;
y = rand(2,10);
figure
yyaxis left
plot(x, y(1,:))
ylabel('y_1') % Left Y-Axis Label
yyaxis right
plot(x, y(2,:))
ylabel('y_2') % Right Y-Axis Label
grid
legend('y_1', 'y_2', 'Location','N') % Legend For Both
See the yyaxis documentation for more details.
  1 Comment
Michael
Michael on 22 Apr 2020
Edited: Michael on 22 Apr 2020
This works if you plot on the left axis first, but there seems to be a bug in order of the plotting. If you try to plot on the right axis first, then switch to the left to plot, and then call legend command, the output is incorrect. Below is an example where I show proper behavior (plotting on left axis, then right) and then I simply switch axis I want to plot on and show that the legend command doesn't output the correct results.
%%Expected Behavior
y1 = 1:10;y2 = 10:-1:1;
>> figure
yyaxis left
plot(x, y1)
ylabel('y_1')
yyaxis right
plot(x, y2)
ylabel('y_2')
grid
legend('y_1', 'y_2', 'Location','N')
Now if you simply switch the yyaxis calls to plot y1 on the right axis and y2 on the left axis, the legend output is incorrect.
figure
yyaxis right %ONLY CHANGED THIS LINE AND...
plot(x, y1)
ylabel('y_1')
yyaxis left %THIS LINE
plot(x, y2)
ylabel('y_2')
grid
legend('y_1', 'y_2', 'Location','N')
If you run this code, you can see that y2 in the legend is shown in red, when is should be shown in blue and visa versa for y1.

Sign in to comment.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!