Merging different legend labels
显示 更早的评论
Hello everyone, I haven't spend much time coding in Matlab so this one might be a little silly question. Similar questions have been asked as far as I can see; but none of the solutions provided worked for me. So here I am asking: As can be seen in the attached code and image, I have a graph consisting of five lines, two of them representing the resulst of the first model (green ones) and the rest representing the second model (blue ones). Could not find a way to add legend label for different colours in editor. When I code and graph without legends and insert legend in the figure window, it happens to be that, as expected, there are five different labels for each line. I want to merge the green and blue ones and I am pretty sure it is possible and it is just me who cannot do it. Also in the future 8 more model results will be added, each of them consisting of one, two or three lines. How can I merge the legend labels?
Thanks in advance!
x1 = [1, 2 ,3, 4, 5];
y1 = [5, 3, 2.8, 1.7, 1.2];
y2 = [6.5, 4.7, 3.5, 1.9, 1.3];
x2 = [1, 2, 3, 4, 5];
y3 = [6, 5.6, 3.1, 2.9, 1.7];
y4 = [5, 4.1, 3.8, 2, 1.5];
y5 = [5, 4, 3, 1.8, 1.4];
plot(x1,y1,x1,y2,'color', 'g'); %Model 1
hold on
plot(x2,y3,x2,y4,x2,y5,'color', 'b'); %Model 2
hold off
grid minor
xlabel('x values')
ylabel('y values')
title('figure 1')
采纳的回答
更多回答(2 个)
One way,
x1 = [1, 2 ,3, 4, 5];
y1 = [5, 3, 2.8, 1.7, 1.2];
y2 = [6.5, 4.7, 3.5, 1.9, 1.3];
x2 = [1, 2, 3, 4, 5];
y3 = [6, 5.6, 3.1, 2.9, 1.7];
y4 = [5, 4.1, 3.8, 2, 1.5];
y5 = [5, 4, 3, 1.8, 1.4];
Model1=plot(x1,y1,x1,y2,'color', 'g'); %Model 1
hold on
Model2=plot(x2,y3,x2,y4,x2,y5,'color', 'b'); %Model 2
hold off
grid minor
xlabel('x values')
ylabel('y values')
title('figure 1')
legend([Model1(1), Model2(1)],'Model 1','Model 2')
x1 = [1, 2 ,3, 4, 5];
y1 = [5, 3, 2.8, 1.7, 1.2];
y2 = [6.5, 4.7, 3.5, 1.9, 1.3];
x2 = [1, 2, 3, 4, 5];
y3 = [6, 5.6, 3.1, 2.9, 1.7];
y4 = [5, 4.1, 3.8, 2, 1.5];
y5 = [5, 4, 3, 1.8, 1.4];
X1=[x1 nan x1]; Y1=[y1 nan y2];
X2=[x2 nan x2 nan x2]; Y2=[y3 nan y4 nan y5];
plot(X1,Y1,'g', X2,Y2,'b'); legend 'Model 1' 'Model 2'
grid minor
xlabel('x values')
ylabel('y values')
title('figure 1')
类别
在 帮助中心 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



