How do I create a legend and include loop variable values in the labels?
661 views (last 30 days)
Show older comments
I created the matrix P with 400 rows, 3 columns (which I call X, Y and Z).
The variables in each row are related by a simple quadratic (Y^2) and intercept term (X):
Z = Y^2 + X
And I created 10 curves, one for each unique value of X with the following code starting by isolating each unique value of X with "PU = unique..."
Please Note: This entire code only takes about 5 seconds to run:
P = [];
for X = 1:1:10
for Y = 0.1:0.1:4
Z = (Y^2) + X;
P = vertcat(P, [X, Y, Z]);
end
end
PU = unique(P(:,1));
PUC = size(PU, 1);
for i = 1:PUC;
Q{i} = P(P(:, 1) == PU(i), :);
q = Q{i};
x = PU(i);
plot(q(:, 2), q(:, 3))
legend(.......which code goes here??...)
hold on
end
hold off
Each line looks the same, and there are no labels. How do I label each line with using the variable x = PU(i) (which runs from 1 to 10) in a legend which will look like: "X = 1", "X=2", "X=3" etc... up to "X = 10", and have a changing colour or line style.
Thanks
D Howard
0 Comments
Accepted Answer
Kevin Holst
on 21 Feb 2012
Edited: MathWorks Support Team
on 9 Nov 2018
When you create a plot, you can specify the legend labels by setting the “DisplayName” property as name-value pair. Set the "DisplayName" property to a character vector of the text that you want to include in the legend. To include a variable value in the text, use “num2str”.
For example:
hold on
for k = 1:10
txt = ['X = ',num2str(k)];
plot(rand(10,1),'DisplayName',txt)
end
hold off
legend show
Starting in R2014b, plotted lines cycle through the colors in the color order.
16 Comments
Nasim Hasanpour
on 21 Jul 2022
Edited: Nasim Hasanpour
on 21 Jul 2022
Thanks. It was so helpful.
Does anyone know how to change the legends' font in this code? I want to use the plot in Latex.
More Answers (4)
Kevin Holst
on 21 Feb 2012
Not in the way that you're currently doing it, but if you're not married to the idea of using your P variable how you currently are using it, I'd suggest something like this:
P = (0.1:0.1:4)';
for i = 2:11
P(:,i) = P(:,1).^2 + (i-1);
legendInfo{i-1} = ['X = ' num2str(i-1)];
end
plot(P(:,1),P(:,2:end))
legend(legendInfo)
The problem with this is that Matlab cycles through 7 different colors, but doesn't switch the line type automatically when it gets through the colors. So the first 3 and last 3 curves will be the same colors. This way does speed up your code quite significantly.
3 Comments
Saad Rabbani
on 1 Nov 2017
Hi, im trying to make a legend for 4 plots that are inside a for loop but then i have an additional plot outside the loop as well. The plot either shows the legend of the 4 plots inside the loop or the one plot i have outside. Im not sure how i can make a legend for all five plots.
Giuseppe Degan Di Dieco
on 5 May 2021
Dear Kevin,
thanks for your tip, it really helped me in setting the labels of a legend in a for loop.
Hope that in 2021, you're still reading the community updates.
Best.
Elgyii
on 26 Jan 2016
% You can simply store all the handles while you plot, for example:
For i = 1 : 10 h(i) = plot(x,y) end legend(h, names) % names should be what you want to write out on legend
1 Comment
Soroush Shahnia
on 7 Jun 2017
Thanks Eligio. The first solution is killing my laptop and it's very slow. This works much faster for me.
amir king
on 28 Sep 2015
I still have problem with the legend. The problem is all the legend are the same line-style. What is missing or what is wrong?please help
this is my code:
for u=1:5 % dfferent U infinity
colorstflex = 'kbgrm';
figure(u); cla; %%for diffrent RE
plotStyle = {'-o','-*','-r.','-s','-^'};
hold on
for k=1:3
Vel_rel(Vel_rel == 0) = NaN;
x_Dmat = repmat(x_D,[5 1]);
plot(x_Dmat,Vel_rel(u,:,k),plotStyle{k},'color',colorstflex(k));hold on
legendInfo{k}=['flex no. ', num2str(k)]); % or whatever is appropriate
legend(legendInfo)
end
end
3 Comments
Brian Sutton
on 14 Mar 2021
I had a similar problem, to create a legend, but not knowing how many plots I would have. I wanted to set the legend dynamically. I looked at answers using the "DisplayName" property while plotting, but I didn't want to rewrite all of my plotting, and in any case ewasn't sure how to use it with plotyy (probably using hax = plot / semilogy construct). Anyway, I managed to do it by adding to the cell array that contains the legend text in a loop related to how many plotlines I might have. I would have either 5 or 4 to start with (depending on a variable status) and up to "L" plots for v"i" Active followed by up to L plots for v"i" Serious, where "i "would be a label (not a vector component) for each legend item, as follows (I left semicolons off end-of-lines for testing, to print what I was creating). This worked very well. The solution was at https://octave.org/doc/v4.2.2/Basic-Usage-of-Cell-Arrays.html although usually I find MatLab (Octave in my case) documentation too arcane.
if (vac_per_day(1) !=0 || vac_eff(1) != 0) %20210314
legend_text = {['All cases'], ['Healthy'], ['All infected'], ['Deaths'], ['Vaccinated']} %5 items
for i = 1:L
legend_text{5+i} = strcat("v", num2str(i), " Active")
legend_text{5+L+i} = strcat("v", num2str(i), " Serious")
endfor
else
legend_text = {['All cases'], ['Healthy'], ['All infected'], ['Deaths']} %4 items
for i = 1:L
legend_text{4+i} = strcat("v", num2str(i), " Active")
legend_text{4+L+i} = strcat("v", num2str(i), " Serious")
endfor
endif
legend = legend(legend_text, 'location', 'southoutside', 'orientation', 'horizontal');
set(legend, 'Interpreter', 'none') %20201218 to stop underscore being lower case if used
Producing (not a pretty chart but) the legend exactly as I wanted (apart from overflowing the box). You can guess this is all to do with Coronavirus modelling. The model numbers are not the realistic UK model, that uses other input data. This is a test harness for calibrating age related subgroups (in other charts)
0 Comments
See Also
Categories
Find more on Data Distribution Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!