Title over a group of subplots - matlab

I want a figure with six plots inside; I split it with subplots. For example
for i = 1:12
subplot(3,4,i)
plot(peaks)
title(['Title plot ',num2str(i)])
end
I would like to add two global titles, let's say a global title for the six plots on the left hand side and another title for the six other plots on the right hand side.
I don't have 2018b version, so I cannot use sgtitle('Subplot Title');. Is it possible use suptitle('my title'); somehow?
I can use text() but resizing the window, the two labels move.

You can use annotation for that, with the location of subplots 1 and 3:
for k = 1:12
sp(k) = subplot(3,4,k);
plot(peaks)
title(['Title plot ',num2str(k)])
end
spPos = cat(1,sp([1 3]).Position);
titleSettings = {'HorizontalAlignment','center','EdgeColor','none','FontSize',18};
annotation('textbox','Position',[spPos(1,1:2) 0.3 0.3],'String','Left title',titleSettings{:})
annotation('textbox','Position',[spPos(2,1:2) 0.3 0.3],'String','Right title',titleSettings{:})

I did not test this, but you can get the handle to a subplot object and then perform the title method on this handle. I would also suggest to then apply the title after the loop.
CODE
for k = 1:12
h(k) = subplot(3, 4, i)
plot(peak)
end
title(h(1), 'Left side')
title(h(8), 'Right side') % find out the right index yourself
Remark:
Do not use i or j as iteration variable for they are already defined in the namespace of MATLAB as imaginary unit.

Related

how to use subplot within two loops

I need one figure with multiple graphs within two loops.
for i=1:length(state)
[block]
for j=1:length(channel)
[block]
subplot(length(state),length(channel)),j)
plot(a,b)% a and b are arrays of doubles.
end
end
I want one figure with size =length(state)*length(channel); for instance I need all the graphs of state(1)within all channels in the first row etc...
But what I get is multiple figures (the length of state).
If I understand well enough here is a way to do it :
figure()
lx = 2;
ly = 3;
for ii = 1:lx
for jj = 1:ly
subplot(lx,ly,ly*(ii-1)+jj)
plot(ii,jj,'o')
end
end
Why ly*(ii-1)+jj?
The syntax of subplot is the following : subplot(nbRows,nbCols,position) and the position is given by an unique index going over all available subplots (see image) which is ly*(ii-1)+jj.

How to label line in Matlab plot

I wrote a code plot 17 lines in the same graph. I want to label all line on the graph . Can u help me ?
clear all
close all
clc
syms w
wn=4000 %rad/s
k=1
for n=0:0.05:0.8
w=0:10:1884;
H=1./sqrt((1-(w/wn).^2)+(2*n*w/wn).^2);
x=w/wn
plot(x,H)
title('Time versus Response Graph of n');
xlabel('Time(s)');
ylabel('Response(m)');
k=k+1
hold on
end
I want to clariy which value is equal to which line.
That's usually done by annotation, and I think it is done manually. Since you have a lot of graphs and not much space, I suggest you use text to add the label at the end of the line. So in the loop add (under ylabel for example)
str = sprintf(' n = %.2f',n);
text(x(end),H(end),str);
This will result in
As you can see there is an overlap in the beginning because the curves are close to each other. You can hardcode a little offset for the first one as follows: (Annotation is graph dependent so I think it's ok to hardcode this)
if n == 0
text(x(end),H(end)+.005,str);
else
text(x(end),H(end),str);
end
Result:
General remarks on your code:
you don't use w symbolic so delete syms w
you don't use k so get rid of it as well
w and x can be moved outside the loop and w/wn can be replaced by x
You can also write this without a loop:
wn=4000; %rad/s
w=0:10:1884;
x=w/wn;
n=0:0.05:0.8;
N = length(n);
H=1./sqrt((1-(ones(N,1)*x).^2)+(2*n.'*x).^2);
plot(x,H)
title('Time versus Response Graph of n');
xlabel('Time(s)');
ylabel('Response(m)');
str = sprintf(' n = %.2f\t',n);
strs = strsplit(str,'\t');
offset = zeros(N,1);
offset(1)=.005;
offset(2)=.001;
text(x(end).*ones(N,1),H(:,end)+offset,strs(1:N));
This way it is easier to adjust the offsets of the different curves. (Note I've added an offset for the second curve as well leading to graph below)
`

Creating a scatter plot in matlab with different colors and markers for two different grouping variables

I seem to be having problems creating a 2D scatter plot in matlab with two grouping variables which displays different colors for one of them and different markers for the other. The variable "score" has the X and Y values and the two grouping variables are "att21" and "att22".
I use the following code:
f=figure;
gscatter(score(:,1), score(:,2), {att21, att22}, 'br', 'xo');
what I'm getting is:
scatter plot
However, what I want to get is blue for L4 and red for L1 and x for Flake and o for Chunk. I would also like the legend to indicate this.
What am I missing?
Thanks for any help...
OK, I think I figured it out. The solution provided by Noel is good only if I know the number of groups in each grouping variable, but unfortunately this is not the case.
So I came up with the solution if using nested loops.
f=figure;
hold on;
marker = '+o*.xsd';
clr = 'rgbymck';
att1v = unique(att1);
att2v = unique(att2);
attv = [att1v; att2v];
att1count = 1;
att2count = 1;
for k=1:length(score)
att1count = 1;
att2count = 1;
while att1count <= length(att1v)
if isequal(att1(k),att1v(att1count))
while att2count <= length(att2v)
if isequal(att2(k),att2v(att2count))
f=scatter(score(k,1),score(k,2),15,clr(att1count),marker(att2count));
end
att2count = att2count + 1;
end
end
att1count = att1count + 1;
end
end
legend(attv);
Now the scatter plot is OK and its supports up to 7 groups in each variable. The only problem I'm left with is that I can't manage to create a Legend which shows the different labels for all the groups.
All I manage to get is this:plot with bad legend
If anyone has a solution for me it will be great...
Thanks alot
When you are grouping by 2 grouping variables, each with 2 categories, you are implicitly creating 4 different groups, so you have to define the color and markers for the 4 groups, in your case
gscatter(score(:,1), score(:,2), {att21, att22}, 'rrbb', 'xoxo');
But since gscatter will repeat the pattern if the defined color or marker is smaller than the number of groups, you can save 2 characters by doing
gscatter(score(:,1), score(:,2), {att21, att22}, 'rrbb', 'xo');
If you don't know the number of groups in each category, you can obtain them with the command unique and count them, and then use that number to create the markers and colors. For your example
marker = '+o*.xsd';
clr = 'rgbymck';
n_groups_att1 = length(unique(att21));
n_groups_att2 = length(unique(att22));
m = marker(1:n_groups_att2);
c = repmat(clr(1:n_groups_att1),n_groups_att2,1);
c = c(:)';
gscatter(score(:,1), score(:,2), {att21, att22}, c, m);
Just make sure that marker and clr has more elements than possible number of groups in each grouping variable

why cant i display both the colorbar's title and ticks simultaneously?

gamma=20;
P=0.1;
N=P.*gamma;
lamdazero=1550;
[lamdapump,lamdasignal] = meshgrid(1540:0.1:1580,1520:0.1:1580);
beta3=0.06;
beta4=-2*10^-4;
c=2*pi*3*10^8;
L=1;
A0=(1./lamdapump) -(1./lamdazero);
B0=(1./lamdapump) -(1./lamdasignal);
Third0=10^-9.*beta3.*(c.^3).*A0.*(B0.^2);
Fourth0=10^-12.*beta4.*(1./2).*c.^4.*(A0.^2).*(B0.^2);
Fourorder=(10^-12).*c.^4.*beta4.*(1/12).*(B0).^4;
deltabeta=Third0+Fourth0+Fourorder;
test2 = deltabeta;
test2(~(deltabeta<=0 & deltabeta>=-4*N)) = nan;
[C,h]=contourf(lamdapump,lamdasignal,test2,[-(4*N):N/2:0],'ShowText','off');
caxis([-8 0]);
xlabel('\lambda_p_u_m_p')
ylabel('\lambda_s_i_g_n_a_l')
title('Contour representing linear phase mismatch in terms of pump and signal wavelength ')
colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'})
h2=colorbar;
HandleOfTitle = get(h2,'Title');
set(HandleOfTitle,'String','\Delta \beta (\gamma P_F_W_M)');
%If i remove the color yticklabel i get my colorbar title and viceversa
%need to know what to do
%The code works just fine
You are creating two colorbars, the second overwrites the first.
colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'})
Creates a colorbar.
h2=colorbar;
Creates another colorbar and removes the first. Get the handle from the first call and remove the second:
h2 = colorbar('YTickLabel',{'-4','-3.5','-3','-2.5','-2','-1.5','-1','-0.5','0'});
Then use the handle to set the title as before.

MATLAB - Labeling Curves During Iteration

I want to show the p value that was used to generate each curve next to each of the curves plotted. Note that since there is a plot of E and -E, the same p value should be next to both. I've been attempting this for a while and I have not come across anything super useful.
t = -3.1;%coupling
a = 1;%distance between r1 and r3
n = 5;%latice vector span in a1 direction
m = 1;%latice vector span in a2 direction
i = -7;%unique axial vector t_hat direction
j = 11;%unique axial vector c_hat direction
max_p = abs((n*(i+j/2)-j*(m+n/2)));%# of unique p values
La = sqrt(3)*sqrt(m^2+n*m+n^2)*a/gcd(2*n+m,2*m+n);%unit cell length
C = sqrt(n^2+n*m+m^2);%circumference of the nanotube
hold on;
for p=0:1:max_p
kt = -pi/La:.05:pi/La;
kc = 2*pi*p/C;
ka1 = kc*a*.5*(2*n+m)/C + kt*a*sqrt(3)*.5*m/C;
ka2 = kc*a*.5*(n+2*m)/C - kt*a*sqrt(3)*.5*n/C;
E = abs(t+t*exp(1i*ka2)+t*exp(1i*ka1));
title_ = sprintf('(%d,%d) Carbon Nanotube Dispersion Diagram',n,m);
title(title_);
xlabel('k_{t}a');
ylabel('Energy (eV)');
plot(kt,E);
plot(kt,-E);
end
There is a command named text that writes comments into the figures,
http://www.mathworks.se/help/techdoc/ref/text.html
with if you can't solve it with that and the to string operation i misunderstood the question
First, do you need to plot both E and -E? Since these are the same except for their sign you don't really add any information to the plot by having -E there as well. However, if you do need both lines, then just construct an array of strings for the legend, during the loop, which has each string included twice (once for E and once for -E).
... Initial calculations ...
hold on;
for p=0:1:max_p
kt = -pi/La:.05:pi/La;
kc = 2*pi*p/C;
ka1 = kc*a*.5*(2*n+m)/C + kt*a*sqrt(3)*.5*m/C;
ka2 = kc*a*.5*(n+2*m)/C - kt*a*sqrt(3)*.5*n/C;
E = abs(t+t*exp(1i*ka2)+t*exp(1i*ka1));
plot(kt,E);
plot(kt,-E);
% Construct array containing legend text
legend_text{2*(p+1)-1} = strcat('p=', num2str(p));
legend_text{2*(p+1)} = strcat('p=', num2str(p));
end
title_ = sprintf('(%d,%d) Carbon Nanotube Dispersion Diagram',n,m);
title(title_);
xlabel('k_{t}a');
ylabel('Energy (eV)');
legend(legend_text)
I am sure there is a more elegant way of constructing the legend text, but the above code works. Also, notice that I moved the calls to xlabel, ylabel and title to outside of the loop. This way they are only called once and not for each iteration of the loop.
Finally, you need to take care to ensure that each iteration of the loop plots with a different line colour or line style (see edit below). You could colour/style each pair of E and -E lines the same for a given iteration of the loop and just display the legend for E (or -E), which would obviously halve the number of legend entries. To do this you will need to hide one of line's handle visibility - this prevents it from getting an item in the legend. To do this use the following in your loop:
plot(kt, E);
plot(kt,-E, 'HandleVisibility', 'off');
% Construct array containing legend text
legend_text{p+1} = strcat('p=', num2str(p));
Finally, it is best to include clear all at the top of your Matlab scripts.
Edit: To have each plotted line use a different colour for each iteration of your loop use something like the following
... initial calculations ...
cmap = hsv(max_p); % Create a max_p-by-3 set of colors from the HSV colormap
hold on;
for p = 0:1:max_p
plot(kt, E, 'Color', cmap(p,:)); % Plot each pair of lines with a different color
plot(kt, -E, 'Color', cmap(p,:));
end