Combine two MATLAB figures with two y axes

9 views (last 30 days)
Hi. I have two MATLAB figures and I want to combine them together, meaning to show them on one plot. These two figures have two y-axes. Unfortunately, the code I am using combines only the figures based on the right Y-axes. Can someone help me with this. I am attaching the fig files.
Dir = 'D:\Original_Plots\';
BinSuffix={''}; % Text_followed by number ID
% Load figures
for j = 1:1:length(BinSuffix)
h1(j) = openfig([Dir prefix1 BinSuffix{j} '.fig'],'reuse');
ax1(j) = gca;
for j = 1:1:length(BinSuffix)
h2(j) = openfig([Dir prefix2 BinSuffix{j} '.fig'],'reuse');
ax2(j) = gca;
% Combine figures
for j = 1:1:length(BinSuffix)
hf = figure(20);
hold on;
fig1 = get(ax1(j),'children');
fig2 = get(ax2(j),'children');
s = gca;
xlabel('x1,x2');hold on;
ylabel('y1'); % on left axis
hold on;
ylabel('y2'); % on right axis
SS on 14 May 2020
Edited: SS on 14 May 2020
HI, thanks for your reply. I have only two files. I want to keep the same locations of the axes positions. Also, how can I adjust the 'Ylim' for both the y-axes on the left and the right?

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 14 May 2020
Edited: Ameer Hamza on 14 May 2020
Try this code
fig1 = openfig('plot_1.fig');
fig2 = openfig('plot_2.fig');
ax1 = findobj(fig1, 'type', 'axes');
yyaxis(ax1, 'left');
line1L = ax1.Children;
yyaxis(ax1, 'right');
line1R = ax1.Children;
ax2 = findobj(fig2, 'type', 'axes');
yyaxis(ax2, 'left');
line2L = ax2.Children;
yyaxis(ax2, 'right');
line2R = ax2.Children;
fig = figure;
ax = axes();
LineL = copyobj([line1L line2L], ax);
yyaxis(ax, 'right');
LineR = copyobj([line1R line2R], ax);
To change the ylimits you can do something like this
yyaxis(ax, 'left');
ax.YLim = [0 2]; % change Ylimits of left axes
yyaxis(ax, 'right');
ax.YLim = [0 2]; % change Ylimits of right axes

More Answers (0)

Community Treasure Hunt

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

Start Hunting!