To programmatically collect the display names of all plotted curves, we use “findall” function in MATLAB to get all axes in the figure and iterate over their children, checking for and storing the “DisplayName” property of each plot object. This process ensures that the names of all curves, regardless of their associated y-axis, are captured and displayed. We need to iterate over the “axesHandles” twice, once for the left axis and once for the right axis, and retrieve the display names of the plotted curves.
Here is the sample MATLAB code to accomplish the same:
x = linspace(0, 10, 100);
y1 = sin(x);
y2 = cos(x);
y3 = sin(x) + cos(x);
y4 = sin(x) - cos(x);
figure;
% Plot on the left y-axis
yyaxis left;
plot(x, y1, 'DisplayName', 'Sine Wave', 'LineWidth', 1.5);
hold on;
plot(x, y2, 'DisplayName', 'Cosine Wave', 'LineWidth', 1.5);
% Plot on the right y-axis
yyaxis right;
plot(x, y3, 'DisplayName', 'Sine + Cosine', 'LineWidth', 1.5);
hold on;
plot(x, y4, 'DisplayName', 'Sine - Cosine', 'LineWidth', 1.5);
legend('show');
yyaxis left;
axesHandles = findall(gcf, 'Type', 'axes');
items = {};
for ax = axesHandles'
children = ax.Children;
for i = 1:length(children)
if isprop(children(i), 'DisplayName') && ~isempty(children(i).DisplayName)
items{end+1} = children(i).DisplayName;
end
end
end
yyaxis right;
for ax = axesHandles'
children = ax.Children;
for i = 1:length(children)
if isprop(children(i), 'DisplayName') && ~isempty(children(i).DisplayName)
items{end+1} = children(i).DisplayName;
end
end
end
disp('Curve Names:');
disp(items);
Please see the attached documentation for the functions referenced:
I hope this helps in resolving the issue.