How to generate legends with data?

조회 수: 4 (최근 30일)
Andrew Ng Chee Wei
Andrew Ng Chee Wei 2022년 7월 14일
답변: Praveen Reddy 2023년 8월 30일
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?

답변 (1개)

Praveen Reddy
Praveen Reddy 2023년 8월 30일
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!

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by