legend in for loop
Show older comments
%%%%%% 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 Comment
Dyuman Joshi
on 5 Sep 2023
@Sankarganesh P did you check the answers below?
Accepted Answer
More Answers (1)
Dinesh
on 4 Sep 2023
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);
Categories
Find more on Legend 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!