Only plotting two of four diagrams in yyaxes - matlab

I am trying to use a plotyy and hold on to plot four diagrams in two y axes and it did not work.
Can anybody see where is the problem?
It only plots the first two diagrams:
load dexpan2Cp;
x1=dexpan2Cp(:,2);
x1=x1/3600;
y1=((dexpan2Cp(:,3)+dexpan2Cp(:,4))/2000)*32.5;
load Dexpan2_2C;
x2=Dexpan2_2C(:,1);
x2=x2/3600;
y2=Dexpan2_2C(:,2);
A = importdata('Scan Session94-Dexpan19.txt','\t',5);
Dexpan19p=A.data;
save('Dexpan19p.mat','Dexpan19p');
x3=Dexpan19p(:,2);
x3=x3/3600;
y3=((Dexpan19p(:,3)+Dexpan19p(:,4))/2000)*32.5;
load Dexpan19C;
x4=Dexpan19C(:,1);
x4=x4/3600;
y4=Dexpan19C(:,2)+3.3;
x1 = x1(x1<115.7); y1 = y1(1: length(x1) , :);
x2 = x2(x2<115.7); y2 = y2(1: length(x2), :);
x3 = x3(x3<115.7); y3 = y3(1: length(x3), :);
x4 = x4(x4<115.7); y4 = y4(1: length(x4), :);
hold off;
figure;
[ax, h1, h2] = plotyy(x1,y1,x2,y2);
set(h1,'g',y1,'DisplayName','1');
set(h2,'b',y2,'DisplayName','2e');
hold(ax(1),'on');
plot(ax(1),x3,y3,'r',y3,'DisplayName','3');
hold(ax(2),'on');
plot(ax(2),x4,y4,'k',y4,'DisplayName','4');
xlabel('Time (h)');
ylabel(ax(1),' Pressure (MPa)');
ylabel(ax(2),'Tempereture (°C)');
legend('show');

You seem to be using invalid syntax, and not telling us what errors you are receiving when executing your code. In particular, your code errors out after plotting the first two lines -- hence why you are only getting 2 lines plotted.
To make it work, four of your lines should be changed to,
set(h1,'Color','g','DisplayName','1');
set(h2,'Color','b','DisplayName','2e');
plot(ax(1),x3,y3,'Color','r','DisplayName','3');
plot(ax(2),x4,y4,'Color','k','DisplayName','4');

Related

Matlab show two fig files in one plot

I am trying to show two fig. files in one plot but it seems harder then expected. How can this be achieved?
Lets say I have two figs.
fig1 = openfig("someFig1.fig");
fig2 = openfig("someFig2.fig");
If you want to display them in the same plot, you can use copyobj:
x = linspace(0,10);
y1 = sin(x);
plot(x,y1)
savefig('test.fig')
y2 = cos(x);
plot(x, y2)
savefig('test2.fig')
fig1 = openfig("test.fig");
fig2 = openfig("test2.fig");
figure
h=subplot(1,1,1); %define subplot of 1x1
%copyobj of each figure on h subplot
copyobj(allchild(get(fig1,'CurrentAxes')),h)
copyobj(allchild(get(fig2,'CurrentAxes')),h)
Output:

Correctly aligning labels for subgroups within a tiledlayout

I want to put 5 plots in a figure using tiledlayout, 2x2 plots at the top then a plot at the bottom that spans two columns. There should be two sets of axis labels: one for the 2x2 plot and another for the bottom plot. My MWE is
x = linspace(-2,2,100);
y1 = sin(x);
y2 = cos(x);
y3 = sin(x).*cos(2*x);
y4 = sin(2*x).*cos(x);
y5 = y3 + y4;
figure('PaperUnits', 'inches', 'PaperSize', [4 6], 'PaperPosition', [0 0 4 6]);
t = tiledlayout(3,2,'TileSpacing','compact','Padding','compact');
nexttile; plot(x,y1); title('y_1');
nexttile; plot(x,y2); title('y_2');
nexttile; plot(x,y3); title('y_3');
nexttile; plot(x,y4); title('y_4');
xlabel(t,'time t_\alpha')
ylabel(t,'amplitude \alpha')
nexttile([1 2]); plot(x,y5); title('y_5');
xlabel('time t_\beta')
ylabel('amplitude \beta')
saveas(gcf,'myfig.jpg')
This gives me the following figure:
I want the amplitude \alpha ylabel and the time t_alpha xlabel to be aligned correctly for the 2x2 plots (as indicated by my red annotations). Is there a way to do this?
I'm using MATLAB R2020a. Note that the tiledlayout function was introduced in R2019b.
An approximation of what you wanted can be achieved by the approach I mentioned in my comment (using a "nested" tiledlayout). The steps necessary to make it work are:
Creating an external vertical layout.
Reserving the first two rows for the nested tiledlayout, by asking a 2-by-1 nexttile, making the resulting axes hidden, and creating a uipanel in its place. Calling uipanel is necessary because the parent of a tiledlayout cannot be another tiledlayout, but it can be a Panel.
Plotting everything in the appropriate panels, and applying the labels accordingly.
x = linspace(-2,2,100);
y1 = sin(x);
y2 = cos(x);
y3 = sin(x).*cos(2*x);
y4 = sin(2*x).*cos(x);
y5 = y3 + y4;
hF = figure('PaperUnits', 'inches', 'PaperSize', [4 6], 'PaperPosition', [0 0 4 6]);
tOut = tiledlayout(hF,3,1);
hAx = nexttile(tOut, [2,1]); hAx.Visible = 'off';
hP = uipanel(hF, 'Position', hAx.OuterPosition, 'BorderWidth', 0);
tIn = tiledlayout(hP,2,2,'TileSpacing','compact','Padding','compact');
nexttile(tIn); plot(x,y1); title('y_1');
nexttile(tIn); plot(x,y2); title('y_2');
nexttile(tIn); plot(x,y3); title('y_3');
nexttile(tIn); plot(x,y4); title('y_4');
xlabel(tIn,'time t_\alpha')
ylabel(tIn,'amplitude \alpha')
hAx = nexttile(tOut); plot(x,y5); title('y_5');
xlabel(hAx, 'time t_\beta')
ylabel(hAx, 'amplitude \beta')
Resulting in:
From here you can try tweaking the individual GUI elements (layouts, axes, panel) to get a result closer to what you wanted.
A completely different route I can suggest is starting with your code and adding the labels for the top 4 plots using the annotation function (instead of xlabel and ylabel).

Histogram of multiple dataset with different dimension in Matlab

I can plot multiple plots with a same dimension in a histogram
x = rand(1000,3);
hist(x);
But I could not plot multiple plots with a different dimension.
x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);
x = [x1 x2 x3]
hist(x)
I get the following error
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Please someone point me to right direction to solve the problem.
Well the problem is indeed that you cant add non size matching vars.
Here is a patch work for you:
the magic is the Nan variable that make your code match
% its bad habits but:
x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);
% make em' all the same size
max_size = max([length(x1),length(x2),length(x3)]);
% add in the ending nan
x1 = [x1; nan(max_size-length(x1), 1)];
x2 = [x2; nan(max_size-length(x2), 1)];
x3 = [x3; nan(max_size-length(x3), 1)];
% plot em' bad
x = [x1 x2 x3];
figure;
hist(x)
Its working great now! (but you know its a bit of a Frankenstein masterpiece :-)
Triple Bar Histogram (3 datasets)
You can use the histogram() function and retrieve the .binCounts of each histogram and concatenate them in a fashion that gives a 10 by 3 array. By calling bar() on this 10 by 3 array you'll get a similar binning graph that shows the histogram of 3 datasets with the bins shown as triple bars. Also a good idea to use the histogram() function as the use of hist() is no longer recommended by MATLAB.
x1 = rand(1100,1);
x2 = rand(1000,1);
x3 = rand(900,1);
h1 = histogram(x1);
Counts_1 = h1.BinCounts;
h2 = histogram(x2);
Counts_2 = h2.BinCounts;
h3 = histogram(x3);
Counts_3 = h3.BinCounts;
Bin_Edges = h3.BinEdges;
Bin_Width = h3.BinWidth;
Bin_Centres = Bin_Edges(1:end-1) + Bin_Width/2;
Counts = [Counts_1.' Counts_2.' Counts_3.'];
bar(Counts);
title("Triple Bar Histogram");
xlabel("Bin Centres"); ylabel("Count");
set(gca,'xticklabel',Bin_Centres);
Ran using MATLAB R2019b

non-homogenous grouped data in MATLAB plotyy()

I have to plot 1 line plot and 3 grouped scatter plots in a single plot window.
The following is the code I tried,
figure;
t1=0:0.1:10;
X = 2*sin(t1);
ts = 0:1:10;
Y1 = randi([0 1],length(ts),1);
Y2 = randi([0 1],length(ts),1);
Y3 = randi([0 1],length(ts),1);
plotyy(t1,X,[ts',ts',ts'],[Y1,Y2,Y3],'plot','scatter');
%plotyy(t1,X,[ts',ts',ts'],[Y1,Y2,Y3],'plot','plot');
The following are my questions,
The above code works if I replace 'scatter' by 'plot' (see commented out line), but 'scatter' works only for 1 data set and not for 3. Why?
How to individually assign colors to the 3 grouped scatter plots or plots?
Read the error message you're given:
Error using scatter (line 44) X and Y must be vectors of the same
length.
If you look at the documentation for scatter you'll see that the inputs must be vectors and you're attempting to pass arrays.
One option is to stack the vectors:
plotyy(t1,X,[ts';ts';ts'],[Y1;Y2;Y3],'plot','scatter');
But I don't know if this is what you're looking for, it certainly doesn't look like the commented line. You'll have to clarify what you want the final plot to look like.
As for the second question, I would honestly recommend not using plotyy. I may be biased but I've found it far to finicky for my tastes. The method I like to use is to stack multiple axes and plot to each one. This gives me full control over all of my graphics objects and plots.
For example:
t1=0:0.1:10;
X = 2*sin(t1);
ts = 0:1:10;
Y1 = randi([0 1],length(ts),1);
Y2 = randi([0 1],length(ts),1);
Y3 = randi([0 1],length(ts),1);
% Create axes & store handles
h.myfig = figure;
h.ax1 = axes('Parent', h.myfig, 'Box', 'off');
h.ax2 = axes('Parent', h.myfig, 'Position', h.ax1.Position, 'Color', 'none', 'YAxisLocation', 'Right');
% Preserve axes formatting
hold(h.ax1, 'on');
hold(h.ax2, 'on');
% Plot data
h.plot(1) = plot(h.ax1, t1, X);
h.scatter(1) = scatter(h.ax2, ts', Y1);
h.scatter(2) = scatter(h.ax2, ts', Y2);
h.scatter(3) = scatter(h.ax2, ts', Y3);
Gives you:
And now you have full control over all of the axes and line properties. Note that this assumes you have R2014b or newer in order to use the dot notation for accessing the Position property of h.ax1. If you are running an older version you can use get(h.ax1, 'Position') instead.

Plotting from different matlab files

I have four matlab codes and each of them generates a plot how can be able to combine all the plots into one plot to show the transition of each?
If you want to plot multiple lines on the same figure you can use hold on For example:
plot(x1,y1,'ok');
hold on
plot(x2,y2,'or');
If you are saying that they all form one single line then try concatenate your input vectors like this:
%Mock input
x1 = 0:9;
x2 = 10:19;
x3 - 20:29;
x4 = 30:39;
y1 = 2*x1 -20;
y2 = 2*x2 -20;
y3 = 2*x3 -20;
y4 = 2*x4 -20;
%Example of plotting concatenated vectors
plot( [x1;x2;x3;x4], [y1;y2;y3;y4]);
If you want all four to be on the same figure (say figure 1) then you can do this:
%% In PlotCode1.m
figure(1)
hold on
...%your plotting code
%% In PlotCode2.m
figure(1)
hold on
...%your plotting code
And if you run each of your PlotCode.m files without closing or clearing figure 1 then all the lines will show up on the same figure.
Alternately, you can turn each of your different plotting files into functions that take in the figure number as an input. For instance:
% In PlotCode1.m
function PlotCode1(num)
figure(num)
hold on
%Your plotting code
% In PlotCode2.m
function PlotCode2(num)
figure(num)
hold on
%Your plotting code
And now you can call each of these functions in one script:
fignum = 2;
PlotCode1(fignum)
PlotCode2(fignum)
And now everything will plot on figure 2.