legend in for loop
Mostrar comentarios más antiguos
%%%%%% 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 comentario
Dyuman Joshi
el 5 de Sept. de 2023
@Sankarganesh P did you check the answers below?
Respuesta aceptada
Más respuestas (1)
Dinesh
el 4 de Sept. de 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);
Categorías
Más información sobre Legend en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!