How do I create a legend and include loop variable values in the labels?

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

 채택된 답변

Kevin Holst
Kevin Holst 2012년 2월 21일
편집: MathWorks Support Team 2018년 11월 9일
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

Is there any way to just to get Matlab to change the plot style itself successively?
Thanks for the answer Kevin, I went with this solution, works fine, but would be nicer not to have to do this.
Very useful! Thank you!
This worked for me. Thanks
this is very helpful :)
Thanks Kevin, and I agree with the pun Astrid made
Benjamin
Benjamin 2019년 4월 16일
편집: Benjamin 2019년 4월 16일
easy and to the point. Thank you, but I have a problem with it and that is when I added this section to my code the colors of the legends are not consistent with the colors of the figures. In fact, the color of of the legend changes for each curve but the color of each curve doesn't change!!
If u dont want to call a variable, u can just put the name directly like so:
plot(X,Y,'DisplayName','Name')
Thanks man.. it helped a lot
sprintf works well here also.
It was super helpful! Thanks!
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.
@Nasim Hasanpour Have you got the answer of your question?

댓글을 달려면 로그인하십시오.

추가 답변 (4개)

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

I found a way to fix this! :)
set(0,'DefaultAxesLineStyleOrder',{'-','--',':'}) %or whatever order you want
This is why I help out on Answers, I learn new useful things! :D
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.
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
Elgyii 2016년 1월 26일

2 개 추천

% 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

Thanks Eligio. The first solution is killing my laptop and it's very slow. This works much faster for me.

댓글을 달려면 로그인하십시오.

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

% 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
So helpful! Many thanks,

댓글을 달려면 로그인하십시오.

Brian Sutton
Brian Sutton 2021년 3월 14일

0 개 추천

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)

카테고리

질문:

2012년 2월 21일

댓글:

2023년 10월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by