我在 Matlab 中制作了一个图表,如果该点在指定的框内,则生成点并绘制一个红色十字,如果它在外面,则绘制一个蓝色圆圈。绘图工作正常,但我发现传说的产生很难正确。仅在绘图末尾添加图例仅显示与绘制的最后一个点相对应的条目。
我最终使用下面的代码让它工作,通过为创建的第一个点创建一个图例,然后在绘制另一种类型的点时,获取当前图例并将新点信息附加到其中。
这看起来真的很啰嗦,有没有更好的方法来为这种绘制点的方式生成图例?
figure;
title('A Graph') ;
hold on;
redhandle = 0
bluehandle = 0
redlegendmade = 0;
bluelegendmade = 0;
for count1 = 1:100
% Get a random point in a circle with radius 5
random_radius = sqrt(5)*rand();
random_angle = 2*pi*rand;
% Set x and y coordinates.
x = random_radius*cos(random_angle);
y = random_radius*sin(random_angle);
% If point inside a box,centred on 0,0 with width = 4 and
% height = 2, draw a red cross, otherwise a blue circle.
if (abs(x)< 2 && abs(y)<1)
% Get a handle to a plotted red point for legend
redhandle = plot(x,y,'rx');
% Actually plot the red point so its visible
plot(x,y,'rx');
% If we haven't already handled the red info for the legend, do so
if (redlegendmade == 0)
% Get current legend
[LEGH,OBJH,OUTH,OUTM] = legend;
% Update legend with red info
legend([OUTH;redhandle],OUTM{:},'In')
% Don't handle red info again
redlegendmade = 1;
end
hold on;
else
% Get handle to plotted blue point for adding to legend
bluehandle = plot(x,y,'bo');
% Actually plot the blue point so it's visible
plot(x,y,'bo');
% If we havent already handled the blue info for legend, do so
if (bluelegendmade == 0)
% Get current legend
[LEGH,OBJH,OUTH,OUTM] = legend;
% Update legend with blue info
legend([OUTH;bluehandle],OUTM{:},'Out')
% Don't handle blue info again
bluelegendmade = 1
end
hold on;
end
end