way to legend a data organized into colours in simple plot?

first_data = [[3 4 8 1];[3 6 4 9]]; % desired legend (first) & color (green)
second_data = [[1 3 5];[3 2 7];[3 4 2]]; % desired legend (second) & color (cyan)
combine = {first_data,second_data}; % recieving new data in every 'for' loop iteration thats why combining
colours = {'g','c'};
Legend_Names = {'first','second'};
for i = 1:length(combine)
plot(cell2mat(combine(i)),'Color',cell2mat(colours(i)),'LineWidth',2); grid on; hold on;
end
legend(Legend_Names)
i wish to plot my each data set with same colour... in this case legend ''Second'' should have ''cyan'' colour

 채택된 답변

Star Strider
Star Strider 2025년 2월 26일
편집: Star Strider 2025년 2월 26일
I am not certain what you want.
One option —
first_data = [[3 4 8 1];[3 6 4 9]]; % desired legend (first) & color (green)
second_data = [[1 3 5];[3 2 7];[3 4 2]]; % desired legend (second) & color (cyan)
combine = {first_data,second_data}; % recieving new data in every 'for' loop iteration thats why combining
colours = {'g','c'};
Legend_Names = {'first','second'};
for i = 1:length(combine)
hp{i} = plot(cell2mat(combine(i)),'Color',cell2mat(colours(i)),'LineWidth',2, DisplayName=Legend_Names{i});
hold on;
end
grid on;
legend([hp{1}(1) hp{2}(1)], Location = 'best')
For either of these, it is necessary to return the handles of each plot call, and pass them to the legend call..
EDIT — Ran code again.
.

댓글 수: 5

Dear Star thanks for your Guidence, i exactly desired what you Guided.
Just Sharing your Code for Release 2019a as i mentiond in question.
first_data = [[3 4 8 1];[3 6 4 9]]; % desired legend (first) & color (green)
second_data = [[1 3 5];[3 2 7];[3 4 2]]; % desired legend (second) & color (cyan)
combine = {first_data,second_data}; % recieving new data in every 'for' loop iteration thats why combining
colours = {'g','c'};
Legend_Names = {'first','second'};
for i = 1:length(combine)
hp{i} = plot(cell2mat(combine(i)),'Color',cell2mat(colours(i)),'LineWidth',2,'DisplayName',cell2mat(Legend_Names(i))); hold on;
end
grid on;
legend([hp{1}(1) hp{2}(1)], 'Location', 'best')
a little guidence further required with last line..
legend([hp{1}(1) hp{2}(1)], 'Location', 'best')
instead of manually defining >> [hp{1}(1) hp{2}(1)] << how can i automate it , lets suppose if i have three data sets combine = {first_data,second_data, third_data};
legend( cellfun(@(C)C(1), hp), 'location', 'best')
Works... Thanks
As always, my (our) pleasure!
(Thanks, @Walter Roberson. I was still sleeping 3 hours ago.)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

제품

릴리스

R2019a

태그

질문:

2025년 2월 26일

댓글:

2025년 2월 26일

Community Treasure Hunt

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

Start Hunting!

Translated by