How do I fill legend on double y axis plot?

2 views (last 30 days)
Niall Harris
Niall Harris on 20 Mar 2023
Answered: Star Strider on 20 Mar 2023
I have a double y axis plot and I have 3 curves on the left axis and 1 on the right. When I add the legend to the plot I can fill out the legend tag for the first 3 curves, but when I try to add the fourth entry an error appears that says there are extra entries. How do I add the tag for the right axis into the legend?

Answers (1)

Star Strider
Star Strider on 20 Mar 2023
Without seeing your code (and your MATLAB version, although I’m not certain how relevant that is in this instance), it’s not possible to determine precisely what the problem is.
Using the 'DisplayName' property works here —
t = linspace(0, 1, 250);
y = sin([1;3;5;7]*2*pi*t);
figure
yyaxis left
hold on
for k = 1:3
hpl(k) = plot(t, y(k,:), 'DisplayName',"Curve "+k);
end
hold off
yyaxis right
hpr = plot(t, y(4,:), 'DisplayName',"Curve "+4);
legend('Location','best')
I added the plot handles in case it’s necessary to pass them as the first argument to the legend call, although that’s not necessary here. It may be necessary for you to use them, so I included them.
.

Community Treasure Hunt

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

Start Hunting!