# Combining two stacked plots

31 views (last 30 days)
bef on 4 Aug 2020
I have two 147x1 tables. I plotted them using the stacked plot option and now have two figures. I was wondering how I can go about overlaying the plots given that they have the same x axis.
figure(1)
plot1 = stackedplot(XArray)
figure(2)
plot2 = stackedplot(YArray)
I tried
plot(plot1,plot2)
but it was invalid

Star Strider on 4 Aug 2020
I have no idea what ‘XArray’ and ‘YArray’ are, or how they may be related. Apparently, they have different numbers of elements, or plotting them against each other would have worked.
One possibility:
Xt = linspace(min(min(XArray),min(YArray)), max(max(XArray),max(YArray)), numel(XArray));
Yt = linspace(min(min(XArray),min(YArray)), max(max(XArray),max(YArray)), numel(YArray));
figure
plot(Xt, XArray)
hold on
plot(Yt, YArray)
hold off
grid
another possibility:
figure
plot(XArray)
hold on
plot(YArray)
hold off
grid
There may still be more possible approaches to this.
.
##### 2 CommentsShowHide 1 older comment
Star Strider on 5 Aug 2020
It would have been nice to have known that detail before.
Each table contains a (147x1) vector. Just extract them to vectors using the table2array function:
XArrayVct = table2array(XArray);
YArrayVct = table2array(YArray);
then make appropriate changes in the respective variable names to my code, and imy code should work without further modification. (There are other ways to extract them, however this is easiest.)

Seth Furman on 17 Nov 2020
In cases such as this one, where the tables we want to plot have the same height, we can concatenate them horizontally and call stackedplot.
For example,
>> XArray = array2table(randi(10,147,1),'VariableNames',{'A'});
>> YArray = array2table(randi(10,147,1),'VariableNames',{'B'});
>> stackedplot([XArray,YArray]) Adam Danz on 19 Nov 2020
Seth Furman's suggestion to concatenate the data prior to creating the stackedplot is a good approach. If that is not an option, for example when the two stackedplots have a different set of x-values, you can create more than 1 stacked plot on a figure by setting the stackedplot parent which can be a:
Figure object | Panel object | Tab object | TiledChartLayout object | GridLayout object
Demo using tiledlayout
fig = figure();
tlo = tiledlayout(fig,1,2);
nexttile(tlo);
stackedplot(rand(40,4),'Parent',tlo)
nexttile(tlo);
stackedplot(rand(55,4),'Parent',tlo) If the two stackedplot objects have the same x-values, you can link the x-axes so the vertical reference line is the same between both object using the method in this answer.

R2020a

### Community Treasure Hunt

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

Start Hunting!