1

Is there a way to create subplots dynamically in matlab ?

I have a variable X that determines the number of graphs to be plotted, i was wondering if there was a way to dynamically create these graphs since X will vary according to a certain scenario

I currently allocate the number of subplots beforehand like so:

figure

ax1 = subplot(3,1,1); 
ax2 = subplot(3,1,2); 
ax3 = subplot(3,1,3); 

plot(ax1,ins,state_vec(:,1),'b',x,100,'r','LineWidth',2)
plot(ax2,ins,state_vec(:,2),'b',x,100,'r','LineWidth',2)
plot(ax3,ins,state_vec(:,3),'b',x,100,'r','LineWidth',2)

3 Answers 3

1

If you only want them in one column (just like you have them now), a simple for loop should do it:

figure

for i = 1:X
    axi = subplot(X,1,i)
    plot(axi,ins,state_vec(:,i),'b',x,100,'r','LineWidth',2)
end

If you want a grid, you'll have to be cleverer than that, but you can do it with two for loops. If you can, try R + ggplot2! :)

Sign up to request clarification or add additional context in comments.

Comments

1

If anyone is still asking this question, MATLAB since R2019b now recommends using the tiledlayout and nexttile function pair to dynamically arrange multiple plots inside one figure, e.g.

tiledlayout('flow')
nexttile
plot(x,y1)
nexttile
plot(x,y2)

Comments

0

If you want it to be a square, you can do:

figure

sqSize = ceil(sqrt(X));
for i=1:X
    subplot(sqSize,sqSize,i);
    <plot stuff>
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.