how to make a custom legend

I have the following picture :

在这里输入图像描述

And I would like to make a legend for it. Basically, I want to make a legend for each type of rectangle. In the legend box, I want to mark each color line according to the type of body which it marks:

  • green line : head
  • yellow line : torso
  • purple line : right arm
  • cyan line : left arm
  • red line : left leg
  • blue line : right leg
  • This is basically custom, because I have more rectangles of each type. How can I do a custom legend and attach it to the figure which draws this picture?


    The simplest way I can think of is to first plot one rectangle of each type and construct a legend for only unique rectangles. Like so:

    figure;
    hold on;
    
    % unique rectangles
    plot(rand(1, 10), 'b');
    plot(rand(1, 10), 'g');
    
    % the rest
    plot(rand(1, 10), 'b');
    plot(rand(1, 10), 'g');
    
    % use normal legend with only as many entries as there are unique rectangles
    legend('Blue', 'Green');
    

    You will have many lines of the same color, but a legend only for unique colors.


    There are 2 ways you could go about this. You could create your squares and then assign them to an hggroup. This way you dont have multiple items for each color. Something like this:

    hold on
    for ii = 1:4
        hb(ii) = plot(rand(1,2), rand(1,2),'color','r'); 
    end
    
    hg = hggroup;
    set(hb,'Parent',hg) 
    set(hg,'Displayname','Legs')
    
    legend(hg)
    

    Or you could create dummy objects, like this:

    hold on
    for ii = 1:4
        hb(ii) = plot(rand(1,2), rand(1,2),'color','r'); 
    end
    
    p = plot([],[],'r');
    
    legend(p,'Legs')
    

    The former is a little more elegant.


    我想添加到dvreed77的使用hggroup的清洁图例使用的答案,我还需要设置'IconDisplayStyle'(Matlab R2014a),以便:

    %4 kinds of lines:
    n_areas = 4;
    n_lines = 10;
    
    %use built-in color map
    cmap = hsv(n_areas);
    
    %plot lines and generate handle vectors
    h_fig = figure;
    hold on
    h_lines = zeros(1,n_lines);
    
    for l = 1:n_areas
    
      for k = 1:n_lines
        h_lines(k) = plot(rand(1,2), rand(1,2),'Color',cmap(l,:));
      end
    
      %Create hggroup and set 'icondistplaystyle' to on for legend
      curPlotSet = hggroup;
      set(h_lines,'Parent',curPlotSet);
      set(get(get(curPlotSet,'Annotation'),'LegendInformation'),...
          'IconDisplayStyle','on');
    end
    
    %Now manually define legend label
    legend('heads','legs','hands','feet')
    
    链接地址: http://www.djcxy.com/p/67290.html

    上一篇: Matlab中多尺度形态学图像简化

    下一篇: 如何制作自定义图例