How to set a legend with a label for two or more lines?
193 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Lemuel Carlos Ramos Arzola
am 7 Feb. 2020
Kommentiert: Adam Danz
am 8 Feb. 2020
Hello,
In the graphic legend I want to share the same label for two or more lines.
For example, I have two (or more) pair of data
x = linspace(0,0.5);
for i = 1:3
y1(i,:) = x.^2 + i;
y2(i,:) = (2*x).^2 + i;
end
My plot instructions are
hold on
plot(x,y1,'-')
set(gca,'ColorOrderIndex',1)
plot(x,y2,'--')
legend({'label 1','label 2','label 3'})
I want that the first curves of y1 and y2 share the label “label 1” and so on for the second and the thirds lines, “label 2” and “label 3”, respectively. Something like this
![figure2.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/270471/figure2.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/270468/image.png)
Thanks in advance for the answers.
10 Kommentare
Adam Danz
am 7 Feb. 2020
I understand. Walter pointed you to a function on the file exchange that might be helpful in building a custom legend.
Akzeptierte Antwort
Jeremy
am 7 Feb. 2020
This isn't a particularly elegant solution, but I think it does what you want.
x = linspace(0,0.5);
for i = 1:3
y1(i,:) = x.^2 + i;
y2(i,:) = (2*x).^2 + i;
end
hold on
plot(x,y1,'-')
set(gca,'ColorOrderIndex',1)
plot(x,y2,'--')
[lh, labelhandles] = legend({'label 1','label 2','label 3'});
labelhandles(5).LineStyle = '--';
labelhandles(4).YData = [0.83 0.83];
labelhandles(5).XData = [0.0460 0.5057]; labelhandles(5).YData = [0.760 0.760];
This will only update one of the legend entries, I trust you can extend this solution to the others. You could also choose a labelhandles variable with a shorter name to make it look a little neater, if you wanted.
Your YData property can be tweaked until you are happy with the appearance.
![plot_legend.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/270480/plot_legend.png)
3 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!