legend in for loop

6 views (last 30 days)
Sankarganesh P
Sankarganesh P on 4 Sep 2023
Commented: Dyuman Joshi on 5 Sep 2023
%%%%%% 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

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 4 Sep 2023
Edited: Dyuman Joshi on 4 Sep 2023
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.

More Answers (1)

Dinesh
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);

Tags

Community Treasure Hunt

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

Start Hunting!