Figure legend mismatch when using gobjects
14 views (last 30 days)
Show older comments
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:

0 Comments
Accepted Answer
VBBV
on 18 Feb 2023
Edited: VBBV
on 18 Feb 2023
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
0 Comments
More Answers (1)
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
See Also
Categories
Find more on Creating, Deleting, and Querying Graphics Objects 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!