legend in for loop
7 次查看(过去 30 天)
显示 更早的评论
%%%%%% 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
采纳的回答
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)
0 个评论
更多回答(1 个)
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!