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!