How to generate legends with data?

1 visualizzazione (ultimi 30 giorni)
Andrew Ng Chee Wei
Andrew Ng Chee Wei il 14 Lug 2022
Risposto: Praveen Reddy il 30 Ago 2023
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?

Risposte (1)

Praveen Reddy
Praveen Reddy il 30 Ago 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!

Tag

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by