How do I create a legend involving multiple plots created in a for loop?

43 ビュー (過去 30 日間)
Kelsey Shipman
Kelsey Shipman 2019 年 4 月 26 日
コメント済み: Belinda Finlay 2020 年 5 月 28 日
I am trying to create a figure with 3 plots and a legend detailing what each plot is. Each plot is created in a for loop.
for j= 1:3
y = j;
figure(1);
plot(y);
hold on;
end
Thus, there will be 3 lines labeled in the legend. I appreciate any help that you all can provide!

回答 (3 件)

Adam Danz
Adam Danz 2019 年 4 月 26 日
編集済み: Adam Danz 2019 年 4 月 26 日
Here are some demos you can follow.
Option 1: add legend labels when you call legend
figure()
axes
hold on
nLoops = 3;
ph = gobjects(1,nLoops);
for j= 1:nLoops
y = randn(10,1)+j;
ph(j) = plot(y, '-o');
end
legend(ph, {'first', 'second', 'third'})
Option 2: add legend labels within the loop
figure()
axes
hold on
nLoops = 3;
ph = gobjects(1,nLoops);
for j= 1:nLoops
y = randn(10,1)+j;
ph(j) = plot(y, '-o', 'DisplayName', sprintf('line %d',j));
end
legend(ph)
  4 件のコメント
Kelsey Shipman
Kelsey Shipman 2019 年 4 月 27 日
I got the error on your sample code and when I adapted it to my own.
MATLAB_R2019a
Adam Danz
Adam Danz 2019 年 4 月 27 日
編集済み: Adam Danz 2019 年 5 月 15 日
I just triple-checked and the two demos I wrote function perfectly in 2019a. What was the error message?
Could you share a reproducible version of your code? I'm sure it's a small error; easy to fix.

サインインしてコメントする。


Image Analyst
Image Analyst 2019 年 4 月 27 日
Try this:
figure()
hold on
numberOfLoops = 3;
for k = 1 : numberOfLoops
y = randn(10,1) + k;
plot(y, '.-', 'MarkerSize', 20, 'LineWidth', 2);
% Make up a string for this particular line plot.
legends{k} = sprintf('This is plot #%d', k);
end
legend(legends) % Display all the legend texts.
grid on;
0000 Screenshot.png
  1 件のコメント
Belinda Finlay
Belinda Finlay 2020 年 5 月 28 日
Thanks, you answer my question - before I even had to ask.

サインインしてコメントする。


Kelsey Shipman
Kelsey Shipman 2019 年 4 月 29 日
I appreciate all of your help. The problem was due to an undiagnosed error at the beginning of my script, so I have figured out the problem, and my legend is now displaying appropriately.

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by