MATLAB : Plot multiple lines in a single graph with different colors and Legend them. - matlab

slip_percent is plotted on y axis vs nInc(Values of 'nInc' and 'numofContacts' are obtained while running the code)
slip_percent = cell(1,numofContacts);
for nC=1:numofContacts
slip_percent{nC} = ShearCapacity(:,(5*nC));
end
Slip_percent{nC}'s are column matrices which should be plotted on same graph using different colors and legend them. If numofContacts(nC) is fixed, then the solution would be simple.
I tried the following code, but it plots all the lines in same color
'Leg' : this array contains the following elements : CaseA,CaseB,-----CaseZ,CaseAA,---,CaseZZ.
Suppose numofContacts = 3, there are 3 columns in slip_percent , then the three columns must be plotted in same graph with different colour and they must be named as CaseA,CaseB and CaseC resp.
hold on
x = linspace(0,nInc);
for g=1:numofContacts
plot(slip_percent{g})
legend(Leg(g));
xlabel('Load Increment');
ylabel('% of Bolt Slip');
hold off
end
Can anyone help me plot the lines in different colors and how to name them ?
Thank You

You can use legend with a string cell array argument to provide several legends.
Also try replacing hold on with hold all
hold all
for g=1:numOfContacts
plot( slip_percent{g});
end
legend( Leg );
xlabel('Load Increment');
ylabel('% of Bolt Slip');

Related

How to draw differently spaced grid lines in Matlab

On mathworks, I have found a code which is suppossed to draw grid lines in a plot:
g_x = -25:1.25:0;
g_y = -35:2.5:-5;
for i = 1:length(g_x)
plot([g_x(i) g_x(i)],[g_y(1) g_y(end)],'k:')% y grid lines
hold on
end
for i=1:length(g_y)
plot([g_x(1) g_x(end)],[g_y(i) g_y(i)],'k:') % x grid lines
hold on
end
here's a link
I don't understand the plot command: e.g. the y grid lines - one of the inputs is a vector containing all the spacing points of the x-axis, where I want to have a grid. These points are given in two columns and they are assigned to the second vector, which only contains the first and the last point shown on the y-axis. As I understand this command, it will for example take the first element g_x(1) and g_y(1) and plot a : , it will then take g_x(2) and g_y(1) and plot :, and so on. But How does it keep on plotting : from g_y(1) continuously until g-y(end) ?
To directly answer your question, it simply plots the two endpoints of each grid line and since the default LineStyle used by plot is a solid line, they will automatically be connected. What that code is doing is creating all permutations of endpoints and plotting those to form the grid.
Rather than creating custom plot objects (if you're using R2015b or later), you can simply use the minor grid lines and modify the locations of the minor tick marks of the axes.
g_x = -25:1.25:0;
g_y = -35:2.5:-5;
ax = axes('xlim', [-25 0], 'ylim', [-35 -5]);
% Turn on the minor grid lines
grid(ax, 'minor')
% Modify the location of the x and y minor tick marks
ax.XAxis.MinorTickValues = g_x;
ax.YAxis.MinorTickValues = g_y;
Basically the code does this:
g_x = -25:1.25:0;
generates a array with values -25.0000 -23.7500 -22.5000 -21.2500 ... 0
These are the positions where vertical lines are drawn
The same holds for g_y, but of course this determines where horizontal lines are drawn.
The option 'k' determined that it is a dashed line.
And the loops just loo through the arrays.
So in the first iteration the plot function draws a line from the position
[-25, -35]
to the position
[-25, -5]
So if you want to change the grid, just change the values stored in g_x
g_x = -25:3.0:0;
would for example draw vertical lines with the width 3.0
I hope this makes sense for you.

Matlab legend for two plots only applies to second plot

I need to plot data of two vectors, and want the data points of each to be shown in a different colour that is explaned in a legend. However, the code below displays only the legend for the second one. What am I doing wrong?
for i_plot = 1 : plot_step : N
subplot(N, 1, i_plot)
h_A = plot(bookmarksA(i_plot, :),0,'b.','MarkerSize',24);
legend('a');
xlim ([0 pieceDuration])
set(gca, 'yTick', []);
title(subj_string(i_plot,:))
hold on
h_Z = plot(bookmarksZ(i_plot, :),0,'r.','MarkerSize',24);
legend(h_Z, 'z');
end
You're only passing one label / handle combination to the legend command at a time. For a given axes, each call to legend overrides previous calls to legend, deleting previous legends rather than adding to an existing legend. You'll want to call legend once with both plot handles and labels.
legend([h_A, h_Z], {'a', 'z'})
Update
Since in your case h_A and h_Z are arrays of plot handles with identical appearances, you can just pass the first item from h_A and h_Z to legend.
legend([h_A(1), h_Z(1)], {'a', 'z'})

Displaying multiple figures with differents colors

I have a matlab code that generates 3D points , so I want to plot each 3D point with different colors.
My last code for generat all points are
figure(i),plot3(mx,my,mz,'r*');
and this one plot all peaks but with same color which are red.
instead of figure(i),plot3(mx,my,mz,'r*'); you can plot each datapoint separately and assign a different color using the property 'Color' of the plot3.
such an example would be:
figure(i),hold on
for j=1:length(mx)
plot3(mx(j),my(j),mz(j),'Color',rand(1,3));
end
hold off
The way each point is coloured is up to you just change the rand to something that makes sense.
What about using e.g. hsv:
M = length(mx);
cols = hsv(M); % specify M colors by hsv
figure(i);
hold on;
for pIdx = 1:M
plot3(mx(pIdx),my(pIdx),mz(pIdx),'Color',cols(pIdx,:));
end

How To Put String Labels on Contours for Contour Plots in MATLAB

I am wondering if it is possible to label the contours of a MATLAB contour plot with a set of user-defined strings?
I am currently using the following code snipper to produce a labelled contour plot:
%Create Data
X = 0.01:0.01:0.10
Y = 0.01:0.01:0.10
Z = repmat(X.^2,length(X),1) + repmat(Y.^2,length(Y),1)';
%Create Plot
hold on
[C,h] = contourf(X,Y,Z);
%Add + Format Labels to Plot
hcl = clabel(C,h,'FontSize',10,'Color','k','Rotation',0);
set(hcl,'BackgroundColor',[1 1 1],'EdgeColor',[0 0 0],'LineStyle','-',)
hold off
The issue with this code is that the labels are automatically generated by MATLAB. Even as I can easily change the contours that are labels, I cannot change the labels that they get.
Ideally, I would like to label them with a set of strings that I define myself. However if that is not possible, then I am wondering if it is possible to change the numeric format of the labels. The reason for this is that the code above actually produce a contour plot for an error rate, which I would like to display as a % value (i.e. use 1% in the contour label, instead of 0.01 etc.).
In this case, hcl is actually an array which stores handles to every contour label on your plot. When you set properties using the array (as in your code),
set(hcl, 'name', 'value')
You will set the property of every label to the same value.
You can change the properties of individual labels by iterating over the array. For example, this is how you would add a percentage sign:
for i = 1:length(hcl)
oldLabelText = get(hcl(i), 'String');
percentage = str2double(oldLabelText)*100;
newLabelText = [num2str(percentage) ' %'];
set(hcl(i), 'String', newLabelText);
end

Plot data with MATLAB biplot with more than 1 color

I have 3 groups of data that had PCA performed on them as one group. I want to highlight each variable group with a different color. Prior to this I overlaid 3 biplots. This gives different colors but creates a distortion in the data as each biplot function skews the data. This caused the groups to all be skewed by different amounts, making the plot not a correct representation.
How do I take a PCA scores matrix (30x3) and split it so the first 10x3 is one color, the next 10x3 is another and the third 10x3 is another, without the data being skewed?
"Skewing" is happening because biplot is renormalizing the scores so the farthest score is distance 1 . axis equal isn't going to fix this. You should use scatter3 instead of biplot
data = rand(30,3);
group = scores(1:10,:)
scatter3(group(:,1), group(:,2), group(:,3), '.b')
hold all
group = scores(11:20,:)
scatter3(group(:,1), group(:,2), group(:,3), '.r')
group = scores(21:30,:)
scatter3(group(:,1), group(:,2), group(:,3), '.g')
hold off
title('Data')
xlabel('X')
ylabel('Y')
zlabel('Z')
Or modify your code's scatter3 lines so that the markers are different colors. The parameter after 'marker' tells what symbol and what symbol and color to plot. E.g. '.r' is a red dot. See Linespec for marker and color parameters.
scatter3(plotdataholder(1:14,1),plotdataholder(1:14,2),plotdataholder(1:14,3),35,[1 0 0],'marker', '.b');
hold on;
scatter3(plotdataholder(15:28,1),plotdataholder(15:28,2),plotdataholder(15:28,3),35,[0 0 1],'marker', '.r') ;
scatter3(plotdataholder(29:42,1),plotdataholder(29:42,2),plotdataholder(29:42,3),35,[0 1 0],'marker', '.g');
This is the method I used to plot biplot data with different colors. The lines of code prior to plot are taken from the biplot.m file. The way biplot manipulates data is kept intact and stops skewing of data when using overlaid biplots.
This coding is not the most efficient, one can see parts that can be cut. I wanted to keep the code intact so one can see how biplot works in it's entirety.
%%%%%%%%%%%%%%%%%%%%%
xxx = coeff(:,1:3);
yyy= score(:,1:3);
**%Taken from biplot.m; This is alter the data the same way biplot alters data - having the %data fit on grid axes no larger than 1.**
[n,d2] = size(yyy);
[p,d] = size(xxx); %7 by 3
[dum,maxind] = max(abs(xxx),[],1);
colsign = sign(xxx(maxind + (0:p:(d-1)*p)));
xxx = xxx .* repmat(colsign, p, 1);
yyy= (yyy ./ max(abs(yyy(:)))) .* repmat(colsign, 42, 1);
nans = NaN(n,1);
ptx = [yyy(:,1) nans]';
pty = [yyy(:,2) nans]';
ptz = [yyy(:,3) nans]';
**%I grouped the pt matrices for my benefit**
plotdataholder(:,1) = ptx(1,:);
plotdataholder(:,2) = pty(1,:);
plotdataholder(:,3) = ptz(1,:);
**%my original score matrix is 42x3 - wanted each 14x3 to be a different color**
scatter3(plotdataholder(1:14,1),plotdataholder(1:14,2),plotdataholder(1:14,3),35,[1 0 0],'marker', '.');
hold on;
scatter3(plotdataholder(15:28,1),plotdataholder(15:28,2),plotdataholder(15:28,3),35,[0 0 1],'marker', '.') ;
scatter3(plotdataholder(29:42,1),plotdataholder(29:42,2),plotdataholder(29:42,3),35,[0 1 0],'marker', '.');
xlabel('Principal Component 1');
ylabel('Principal Component 2');
zlabel('Principal Component 3');
I am not sure if it will help, but try axis equal after you have overlaid the plots.