How to add pairs of graphs (generated through a function) to adjacent subplots?
조회 수: 2 (최근 30일)
이전 댓글 표시
How to add pairs of graphs (generated through a function) to adjacent subplots?
The function "myfunction" produces two graphs, saved as Fig1 and Fig2. At every iteration of the loop for, i.e. i = 1, 3, 5, I would like to add Fig1 and Fig2 to two adjacent subplots, i.e. subplot(3,2,i) and subplot(3,2,i+1), respectively. I tried to do that with the following code, but it does not perform what I would like:
for i = [1 3 5]
[Fig1,Fig2] = myfunction;
subplot(3,2,i); Fig1;
subplot(3,2,i+1); Fig2;
end
function [Fig1,Fig2] = myfunction
Fig1 = figure; plot(1:10,rand(10,1));
Fig2 = figure; scatter(1:10,rand(10,1));
end
Any suggestion, to get the following (desired) output?
채택된 답변
Voss
2023년 10월 30일
One way is to modify myfunction to take two axes as inputs and plot into those.
figure();
for i = [1 3 5]
ax1 = subplot(3,2,i);
ax2 = subplot(3,2,i+1);
myfunction_new([ax1,ax2]); % myfunction_new defined below
end
If you cannot modify myfunction, then you can use copyobj to copy the contents of each figure's axes into a subplot axes. This won't copy legends or colorbars, but you can try to adapt it. I think modifying myfunction is probably the better idea.
f = figure();
for i = [1 3 5]
[Fig1,Fig2] = myfunction(); % myfunction defined below (same as in your question)
figure(f)
ax1 = subplot(3,2,i);
copyobj(allchild(get(Fig1,'CurrentAxes')),ax1);
ax2 = subplot(3,2,i+1);
copyobj(allchild(get(Fig2,'CurrentAxes')),ax2);
delete([Fig1,Fig2]);
end
function myfunction_new(ax)
if ~nargin || numel(ax) < 2
% If fewer than two axes are given, create two new figures and store
% their axes. (This reproduces the current behavior of myfunction,
% which takes no inputs and always creates two new figures.)
figure()
ax = gca();
figure()
ax(2) = gca();
end
plot(ax(1),1:10,rand(10,1));
scatter(ax(2),1:10,rand(10,1));
end
function [Fig1,Fig2] = myfunction
Fig1 = figure; plot(1:10,rand(10,1));
Fig2 = figure; scatter(1:10,rand(10,1));
end
댓글 수: 7
Dyuman Joshi
2023년 10월 30일
You are welcome!
And yes, you can modify the function according to your requirements.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Subplots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!