我有以下图片:
我想为它创造一个传奇。基本上,我想为每种类型的矩形制作一个图例。在图例框中,我想根据它标记的主体类型标记每条颜色线:
- 绿线:头部
- 黄线:躯干
- 紫线:右臂
- 青色线:左臂
- 红线:左腿
- 蓝线:右腿
这基本上是自定义的,因为我有更多的每种类型的矩形。如何制作自定义图例并将其附加到绘制此图片的图形上?
有两种方法可以解决这个问题。您可以创建正方形,然后将它们分配给 hggroup。这样你就没有每种颜色的多个项目。像这样的东西:
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)
或者您可以创建虚拟对象,如下所示:
hold on
for ii = 1:4
hb(ii) = plot(rand(1,2), rand(1,2),'color','r');
end
p = plot([],[],'r');
legend(p,'Legs')
前者更优雅一些。
我想添加到 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')
我能想到的最简单的方法是首先为每种类型绘制一个矩形,然后为唯一的矩形构造一个图例。像这样:
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');
您将有许多相同颜色的线条,但只有独特颜色的图例。
只需在情节外绘制图例点:
figure;
plot(-1,-1,'gs',-1,-1,'b^',-1,-1,'ro');
legend('x1','x2','x3','Location','NorthWest');
xlim([0,1]); ylim([0,1]);
为了控制图例条目的外观,绘制具有值的点,NaN
然后将返回的对象plot
和标签数组传递给legend
函数(NaN
点在图中不可见,但出现在图例中)。
colors = ["red", "blue"];
labels = ["this is red", "this is blue"];
% We 'plot' a invisible dummy point (NaN values are not visible in plots),
% which provides the line and marker appearance for the corresponding legend entry.
p1 = plot(nan, nan, colors(1));
hold on
p2 = plot(nan, nan, colors(2));
% Plot the actual plots. You can change the order of the next two function calls
% without affecting the legend.
plot([0, 1], [0, 1], colors(1));
plot([0, 1], [1, 0], colors(2));
legend([p1, p2], labels)
如果调用时的绘图[p1, p2]
不在当前图形legend([p1, p2], labels)
中,则会引发以下错误:
Invalid argument. Type 'help legend' for more information.
您可以使用以下方式过滤不在当前图中的图:
plots_in_figure = findall(gcf,'Type','Line');
plots_for_legend_indices = ismember([p1, p2], plots_in_figure);
plots_for_this_legend = this.plots_for_legend(plots_for_legend_indices);
legend(plots_for_this_legend, labels)