Home > Software engineering >  How to generate unaligned subplots using tiledlayout?
How to generate unaligned subplots using tiledlayout?

Time:11-03

I plan to generate a plot that has 3 subplots on the first row, 4 subplots on the second row using tiledlayout. As 4 is not a multiple of 3, I have difficulties to correctly manage it. All examples I have seen are aligned subplots (tiles) though.

Normally I will do that with something like:

subplot(2,3,1); plot(...);
subplot(2,3,2); plot(...);
subplot(2,3,3); plot(...);
subplot(2,4,5); plot(...);
subplot(2,4,6); plot(...);
subplot(2,4,7); plot(...);

Is it possible to achieve this goal by using tiledlayout?

CodePudding user response:

Method 1: Continuing to Use subplot()

If you wish to continue using the subplot() function you can use the Lowest-Common-Multiple (LCM) of 3 and 4 in this case. In this case using a subplot grid that has 2 rows and 12 columns will suffice. The key to this method is to have the subplots span multiple positions. The 3rd argument in the subplot() function will dictate the positions that each subplot will span over from start to end. I find that the subplot and span concept carries over to many languages which is a reason why I tend to use it over tiledlayout().

Subplot Positions

Subplots Graphs 1

clf;
subplot(2,12,1:4); plot(rand(5,1));
subplot(2,12,5:8); plot(rand(5,1));
subplot(2,12,9:12); plot(rand(5,1));
subplot(2,12,13:15); plot(rand(5,1));
subplot(2,12,16:18); plot(rand(5,1));
subplot(2,12,19:21); plot(rand(5,1));
subplot(2,12,22:24); plot(rand(5,1));

Subplot Graphs 2

clf;
subplot(2,12,2:4); plot(rand(5,1));
subplot(2,12,5:7); plot(rand(5,1));
subplot(2,12,8:10); plot(rand(5,1));
subplot(2,12,13:15); plot(rand(5,1));
subplot(2,12,16:18); plot(rand(5,1));
subplot(2,12,19:21); plot(rand(5,1));
subplot(2,12,22:24); plot(rand(5,1));

Method 2: Using tiledlayout()

Grid_Height = 2; Grid_Width = 12;
tiledlayout(Grid_Height,Grid_Width);

Position = 1; Height = 1; Width = 4;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 5; Height = 1; Width = 4;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 9; Height = 1; Width = 4;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 13; Height = 1; Width = 3;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 16; Height = 1; Width = 3;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 19; Height = 1; Width = 3;
nexttile(Position,[Height,Width]);
plot(rand(5,1));

Position = 22; Height = 1; Width = 3;
nexttile(Position,[Height,Width]);
plot(rand(5,1));
  • Related