Matlab:需要为绘制点动态创建图例

时间:2013-10-18 18:03:22

标签: matlab graph legend

我在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

1 个答案:

答案 0 :(得分:0)

您可以为每个点设置一个图例句柄,然后只使用第一个和最后一个。

figure;
hold on;
for ii = 1:10
    if ii<5
        h(ii,1) = plot(rand,rand,'rx');
    else
        h(ii,1) = plot(rand,rand,'bo');
    end
end
legend([h(1) h(end)],{'red', 'blue'})

您可以根据点的顺序更改1end索引。