How to group individual plotted lines into one legend item
6 次查看(过去 30 天)
显示 更早的评论
I have the following contour plot from this code. I'd like to group some of the lines I've made into one legend item. Alternatively, how can I plot in one line of code 3 line segments? I know there's an efficient way to do what I'm doing here...
Any help is appreciated.
f = @(x1, x2) 5*(x1).^2 + 7*(x2).^2 - 5*(x1) - 10*(x1).*(x2) + (x2) ;
%paths taken by each method in array for easy reference
%SD,FR,DFP,FBGS,N
SD = [5,2;3.8375,2.9765;2.3910,1.2546;2.0951,1.5032];
FR = [3.8375,2.9765;1.5,1];
DFP = [3.8375,2.9765;1.5185,0.9869;1.5320,1.0050;1.5414,1.0117];
BFGS = [3.8375,2.9765;2.4373,1.2832;2.1198,1.5279;1.7444,1.0738];
P = [5,2;2.1382,1.6729;1.5,1];
N = [5,2;1.5,1];
fcontour(f,[-2 6 -1 4],'LevelList',[-3 0 5 10 20 30 50 100]);
hold on
plot(1.5,1,'o') %optimal point
plot([SD(1,1),SD(2,1)],[SD(1,2),SD(2,2)]) %group 1
plot([SD(2,1),SD(3,1)],[SD(2,2),SD(3,2)]) %group 1
plot([SD(3,1),SD(4,1)],[SD(3,2),SD(4,2)]) %group 1
plot([FR(1,1),FR(2,1)],[FR(1,2),FR(2,2)]) %group 2
plot([DFP(1,1),DFP(2,1)],[DFP(1,2),DFP(2,2)]) %group 3
plot([DFP(2,1),DFP(3,1)],[DFP(2,2),DFP(3,2)]) %group 3
plot([DFP(3,1),DFP(4,1)],[DFP(3,2),DFP(4,2)]) %group 3
plot([BFGS(1,1),BFGS(2,1)],[BFGS(1,2),BFGS(2,2)]) %group 4
plot([BFGS(2,1),BFGS(3,1)],[BFGS(2,2),BFGS(3,2)]) %group 4
plot([BFGS(3,1),BFGS(4,1)],[BFGS(3,2),BFGS(4,2)]) %group 4
plot([P(1,1),P(2,1)],[P(1,2),P(2,2)]) %gruop 5
plot([P(2,1),P(3,1)],[P(2,2),P(3,2)]) %group 5
plot([N(1,1),N(2,1)],[N(1,2),N(2,2)]) %group 5
legend('F(x1,x2)','optimal','SD','FR','DFP','BFGS','P','N')
title('Contour Plot of F(x1,x2)')
xlabel('x1')
ylabel('x2')
0 个评论
采纳的回答
Walter Roberson
2020-2-20
You cannot do what you want to do.
You have two choicesb
1. record the handles returned by the graphic operations. Pass one member from each group as the first parameter to legend. This approach can work well in many cases.
2. Sometimes you have groups you want to legend that do not correspond exactly to graph objects. For example you might want to legend each different color that you generate with a single scatter(), or you want to legend by line pattern ignoring line color. In such a case you can not bother to record the handles of any of those objects. Instead, generate new objects with the desired legend appearance but coordinates nan or inf, and record those handles and pass them to legend as the first parameter. Using nan or inf forces them to not be drawn in the main plot, but legend will still create entries
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Legend 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!