Adding Non-Plotted Items to Figure Legend
Show older comments
Hi,
I have a code that generates a plot of the coefficient of variation for torque generated over a certain range of motion (knee joint angle of 30-85°) by an injured leg in red and the uninjured leg in blue. Afterward, I manually added black lines in the figure window representing the angles where peak torque is produced for each leg (solid = injured, dashed = uninjured) to show that this isn't necessarily where the peak CoV is occurring. I want to show in the legend that the black solid line represents the angle of peak torque for the injured leg and the dashed is for the uninjured, but I'm not sure how to do this since they aren't plotted data points, just lines I manually added. I've attached a picture of the graph for reference. I'm using the R2021b version of MATLAB.
Any advice would be greatly appreciated, thanks!
1 Comment
Fawad Khan
on 29 Oct 2022
I don' think MATLAB provides handles to these objects added manually. You can select the line in the figure and execute the command
l = get(gco);
and test whether it has any properties associated to legend or not.
Although. it is better to plot these lines using MATLAB commands. For example
figure;hold on;
h1 = plot(involved_x,involved_y,%other properties);
h2 = plot(uninvolved_x,uninvolved_y,%other properties);
h3 = plot;% Other data
h4 = plot;% Other data
...
yl = ylim;
h5 = line([52,52],yl,'linestyle','-','color','k','linewidth',2)
h6 = line([53,53],yl,'linestyle','--','color','k','linewidth',2)
legend([h1,h2,h5,h6],{'Involved','Uninvolved','Injured','Uninjured'},%other properties)
Answers (1)
Perhaps something like this —
x = 1:20;
y(1,:) = 0.5+randn(size(x))*0.1;
y(2,:) = 0.5+randn(size(x))*0.1;
figure
plot(x, y(1,:), 'DisplayName','Involved')
hold on
plot(x, y(2,:), 'DisplayName','Uninvolved')
plot(NaN, NaN, '-k', 'LineWidth',2, 'DisplayName','Solid Black Line')
plot(NaN, NaN, '--k', 'LineWidth',2, 'DisplayName','Dashed Black Line')
hold off
legend('Location','best')
ylim([0 1])
figure
plot(x, y(1,:), 'DisplayName','Involved')
ylim([0 1])
hold on
plot(x, y(2,:), 'DisplayName','Uninvolved')
plot([1 1]*8, ylim, '-k', 'LineWidth',2, 'DisplayName','Solid Black Line')
plot([1 1]*9, ylim, '--k', 'LineWidth',2, 'DisplayName','Dashed Black Line')
hold off
legend('Location','best')
.
Categories
Find more on Legend 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!
