Hi,
To create a figure with two sets of y-axes sharing a common x-axis, you can use the MATLAB function yyaxis. This function specifies the active side for the axes instead of the current axes. If the axes do not already include two y-axes, this command adds a second y-axis.
In MATLAB, the legend function allows only one legend per axes. To work around this limitation, you can follow these steps:
- Create a legend for the first set of plot objects.
- Create a new set of axes `a` with the same position as the current axes but turn off its visibility.
- Create another legend referencing the next set of plot objects and associate it with the invisible axes `a` to avoid conflicts with the first legend.
Please refer to the following example code demonstrating the implementation discussed above:
hf = figure;
% Define your data
t = 0:0.1:10; % Example x-axis data
volt = [sin(t); cos(t); sin(2*t); cos(2*t)]; % Example y-axis data for left y-axis
Inte_p = [1.5*t; 2*t]; % Example y-axis data for right y-axis
% Define colors
colors = lines(6); % Generate a set of colors
% Create left y-axis plots
yyaxis left
p1(1) = plot(t, volt(1,:), 'Color', colors(1,:)); hold on;
p1(2) = plot(t, volt(2,:), 'Color', colors(2,:));
p1(3) = plot(t, volt(3,:), 'Color', colors(3,:));
p1(4) = plot(t, volt(4,:), 'Color', colors(4,:));
ylabel('AC (V.)');
yl = max(ylim);
yticks(0:yl);
% Create right y-axis plots
yyaxis right
p2(1) = plot(t, Inte_p(1,:), 'Color', colors(5,:), 'LineStyle', '--'); hold on;
p2(2) = plot(t, Inte_p(2,:), 'Color', colors(6,:), 'LineStyle', '-.');
ylabel('I (A)');
yticks(0:20:100);
% Create the first legend
legend([p1(1), p1(2), p1(3), p1(4)], {'OHM1', 'OHM2', 'OHM3', 'OHM4'}, 'Location', 'southwest');
% Create new axes with visibilty off to avoid interference with the existing plot visually.
a=axes('position',get(gca,'position'),'visible','off');
% Create the second legend associated with the invisible axes a to avoid conflicts with the first legend.
legend(a, [p2(1), p2(2)], {'Int1', 'Int2'}, 'Location', 'northeast');
% Set common x-axis label
xlabel('Time (s)');
hold off;
Kindly refer to following MathWorks documentation to know more about the yyaxis function discussed above: https://www.mathworks.com/help/matlab/ref/yyaxis.html?searchHighlight=yyaxis&s_tid=srchtitle_support_results_1_yyaxis
I hope the solution provided above is helpful.