Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
980 views
in Technique[技术] by (71.8m points)

matlab - Add custom legend without any relation to the graph

I wish to insert a legend that is not related to the graph whatsoever:

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

Now I wish to add it to another figure:

figure;
t=linspace(0,10,100);
plot(t,sin(t));
%% ADD THE LEGEND OF PLOT ABOVE 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is how I have solved this problem in the past:

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');

This will plot the additional points, but because the coordinates are at NaN they will not be visible on the plot itself:

enter image description here

EDIT 26/10/2016: My original answer results in greyed out legend entries in 2016b. The updated code above works, but the answer below is only relevant pre-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');

This will plot the additional points, but they will not be visible on the plot itself.

You can also use copyobj to copy graphics elements from one figure to another if you have a lot of elements, then use set(x, 'visible', 'off') to hide them before showing the legend, but it depends on what your final application is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...