添加与图表无关的自定义图例

Add custom legend without any relation to the graph

我想插入一个与图表无关的图例:

figure;
hold on;
plot(0,0,'or');
plot(0,0,'ob');
plot(0,0,'ok');
leg = legend('red','blue','black');

现在我想把它加到另一个图中:

figure;
t=linspace(0,10,100);
plot(t,sin(t));
%% ADD THE LEGEND OF PLOT ABOVE 

你的问题有点不清楚。不过,我看的时候首先想到的是Matlab中的text函数

您可以使用 text 函数向 Matlab 图形添加文本。它的用途是

>> text(x, y, str);

其中 xy 是图中要添加文本 str 的坐标。您可以使用 textColor 选项来绘制颜色和 TeX 来绘制线条甚至 _。我对使用文本的情节非常有创意。

这是一个用 text

模拟 legend 的快速而肮脏的例子
x = 0:pi/20:2*pi;
y = sin(x);
plot(x,y)
axis tight

legend('sin(x)');

text(5.7, 0.75, 'sin(x)');
text(5.1, 0.78, '_____', 'Color', 'blue');

产生

对于这种特定情况,您可以使用特定命令(在评论中由@Hoki 注明)。

ht = text(5, 0.5, {'{\color{red} o } Red', '{\color{blue} o } Blue', '{\color{black} o } Black'}, 'EdgeColor', 'k');

生产

通过检索 text 对象的句柄,将其复制到新图形 copyobj(ht, newfig) 变得微不足道。 []

我以前是这样解决这个问题的:

figure
t=linspace(0,10,100);
plot(t,sin(t));
hold on;

h = zeros(3, 1);
h(1) = plot(NaN,NaN,'or');
h(2) = plot(NaN,NaN,'ob');
h(3) = plot(NaN,NaN,'ok');
legend(h, 'red','blue','black');

这将绘制附加点,但由于坐标位于 NaN,因此它们在绘图本身上不可见:

编辑 26/10/2016: 我的原始答案导致 2016b 中的图例条目变灰。上面更新的代码有效,但下面的答案仅适用于 2016b 之前:

figure
t=linspace(0,10,100);
plot(t,sin(t));
hold on;

h = zeros(3, 1);
h(1) = plot(0,0,'or', 'visible', 'off');
h(2) = plot(0,0,'ob', 'visible', 'off');
h(3) = plot(0,0,'ok', 'visible', 'off');
legend(h, 'red','blue','black');

这将绘制额外的点,但它们在图本身上不可见。

如果元素很多,也可以使用copyobj将图形元素从一个图形复制到另一个图形,然后在显示图例之前使用set(x, 'visible', 'off')隐藏它们,但这取决于你的最终申请是什么。