Figure legend mismatch when using gobjects

14 views (last 30 days)
I was trying to assign legends to a series of Line objects in a gobjects array. I expected the legends to be assigned to the 6 thin solid lines. However, they seemed to be assigned to 6 lines with different line width and style (see the code and figure below). I would like to know if I misused gobjects or legend.
My code:
figure;
GObjects = gobjects(18,1);
colors = [blue; orange; yellow; purple; green; sky]; % user-defined colors: [r g b]
for i = 1:6
GObjects(i) = line(0:200,data_normal(:,i+3),'Color',colors(i,:),'UserData',i);
GObjects(i+6) = line(200:400,data_down(:,i+3),'Color',colors(i,:),'LineWidth',1,'LineStyle',':','UserData',i+6);
GObjects(i+12) = line(200:400,data_up(:,i+3),'Color',colors(i,:),'LineWidth',1,'UserData',i+12);
end
legend("r bound","m bound","ns bound","r elong","m elong","free")
% I also tried:
%
% legends = ["r bound","m bound","ns bound","r elong","m elong","free"];
% for i = 1:6
% legend(GObjects(i),legends(i))
% end
My result:

Accepted Answer

VBBV
VBBV on 18 Feb 2023
Edited: VBBV on 18 Feb 2023
Check the answer given by @Steven Lord in the below link
https://in.mathworks.com/matlabcentral/answers/244707-how-to-change-order-of-legends
figure;
GObjects = gobjects(18,1);
colors = [blue; orange; yellow; purple; green; sky]; % user-defined colors: [r g b]
for i = 1:6
GObjects(i) = line(0:200,data_normal(:,i+3),'Color',colors(i,:),'UserData',i);
GObjects(i+6) = line(200:400,data_down(:,i+3),'Color',colors(i,:),'LineWidth',1,'LineStyle',':','UserData',i+6);
GObjects(i+12) = line(200:400,data_up(:,i+3),'Color',colors(i,:),'LineWidth',1,'UserData',i+12);
end
legend(GObjects(:)) % from that answer

More Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 18 Feb 2023
Try this syntax:
figure;
GObjects = gobjects(18,1);
L = {"r bound","m bound","ns bound","r elong","m elong","free"};
colors = [blue; orange; yellow; purple; green; sky]; % user-defined colors: [r g b]
for i = 1:6
GObjects(i) = line(0:200,data_normal(:,i+3),'Color',colors(i,:),'UserData',i);
GObjects(i+6) = line(200:400,data_down(:,i+3),'Color',colors(i,:),'LineWidth',1,'LineStyle',':','UserData',i+6);
GObjects(i+12) = line(200:400,data_up(:,i+3),'Color',colors(i,:),'LineWidth',1,'UserData',i+12);
LL{i} = L{i};
legend(LL{:})
end
  1 Comment
Tairan
Tairan on 18 Feb 2023
It doesn't work. The result is the same. The problem seems to relate to the construction order of lines.

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Tags

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!