필터 지우기
필터 지우기

legend in for loop

조회 수: 9 (최근 30일)
Sankarganesh P
Sankarganesh P 2023년 9월 4일
댓글: Dyuman Joshi 2023년 9월 5일
%%%%%% legend are showing like data1 data2 data3 instead of gr26 gr34 gr 42
figure()
temp_grain=[26 34 42];
my_legend = legend();
hold on, grid on
for igrain=1:50
if(igrain==temp_grain(1) || igrain==temp_grain(2) || igrain==temp_grain(3))
disp(igrain)
plot(area_nor(igrain,:),'*-','LineWidth',0.1)
hold on
my_legend.String{igrain} = ['gr(',num2str(igrain),')'];
end
end
Thankz in advance
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2023년 9월 5일
@Sankarganesh P did you check the answers below?

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

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 9월 4일
편집: Dyuman Joshi 2023년 9월 4일
If you only want to plot for the values in temp_grain, use it as the loop index -
temp_grain=[26 34 42];
figure()
hold on
grid on
for igrain=temp_grain
disp(igrain)
plot(area_nor(igrain,:),'*-','LineWidth',0.1)
end
%Make string for legend using the variable temp_grain
str = "gr(" + temp_grain + ")"
%Define legend
legend(str)
You can also use compose to generate the string for legend.

추가 답변 (1개)

Dinesh
Dinesh 2023년 9월 4일
Hi Sankarganesh.
You're trying to replace the default legend entries (like "data1", "data2", etc.) with custom strings, but the way you're attempting to do this is not the typical approach to setting legend entries in MATLAB.
In your approach, you attempt to update the legend strings after each plot within the loop:
my_legend.String{igrain} = ['gr(',num2str(igrain),')'];
You've created the "legend" object before populating it with any strings. The "legend" function typically auto-generates its strings based on existing plot data. Since no data has been plotted yet when you create the legend, it defaults to strings like "data1", "data2", etc.
To resolve this, I have come up with a different approach.
Instead of setting the legend inside the loop, I collect the necessary legend strings in a cell array. This ensures that the order of the legend strings matches the order of the plotted data series. Now, I can set the legend after all the plotting is completed.
The following is a modified version of your code:
figure()
temp_grain = [26 34 42];
hold on, grid on
legend_entries = {}; % Cell array to collect legend entries
for igrain = 1:50
if any(igrain == temp_grain) % does the same check as your if statement, but shorter
disp(igrain)
plot(area_nor(igrain,:), '*-', 'LineWidth', 0.1)
% Add to the legend entries
legend_entries{end+1} = ['gr(', num2str(igrain), ')'];
end
end
% Now set the legend
legend(legend_entries);

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by