How to generate legends with data?
4 views (last 30 days)
Show older comments
Hello,
I'm currently working on an app whereby I can add multiple velocities to calculate for height and range. I met with an issue where when I want to add legends to numerous graphs with the legend naming like : "36", "42" as they represent the velocity. However, the number of plots are not predetermined and is added according to the user's content. Hence, how should I display legends automatically as it adds more plots with data retrieval?
0 Comments
Answers (1)
Praveen Reddy
on 30 Aug 2023
Hi Andrew,
I understand that you want to display legends for unknown number of plots with dynamically changing data. You can use “legend” function in MATLAB along with cell arrays to store the legend names. Please refer to the below example to achieve this.
% Example data for velocities and corresponding heights
velocities = [36, 42, 48, 54]; % Example velocities
heights = [10, 15, 20, 25]; % Example heights
% Create an empty cell array to store legend names
legendNames = cell(1, numel(velocities));
% Plot the data and store legend names
hold on
for i = 1:numel(velocities)
% Generate data for each velocity (example calculation)
x = linspace(0, 10, 100);
y = heights(i) * sin(velocities(i) * x);
% Plot the data
plot(x, y);
% Store the legend name
legendNames{i} = num2str(velocities(i));
end
hold off
% Display the legend
legend(legendNames, 'Location', 'best');
You can dynamically update the "velocities" and "heights" arrays based on user input.
Hope this helps!
0 Comments
See Also
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!