简体   繁体   中英

MATLAB: how to add custom legend to any plot

How do I add custom legend to any plot?
For example:

figure(200)
plot(t1:k,Pexact(t1:k,1),'-xk');
plot(t1:k,xh(1,t1:k),'-sr');

and then I want use the same codes to add plots

hold on plot(t1:k,xh(1,t1:k),'-sb');

and then I want to add a legend for all three plots

if exist('hl','var')
clear hl
end
hold on
hl(1) = plot(t1,0,'-sr');
hl(2) = plot(t1,0,'-sb');
hl(3) = plot(t1,0,'-xk');
set(hl,'LineWidth',2);
set(hl,'Visible','off');
legend(hl,'SC-PF','PF','Truth',...
    'Location','NorthWest');
  • Note: change 0,0 to ax,y coordinate that exist inthe originals plots.

I much prefer defining the legend when I call out the plot. If data are missing from a particular set, or you have conditionals set so that not all data are plotted every time, this method makes a lot more sense.

figure(fig)
hold on
plot(t1:k,Pexact(t1:k,1),'-xk','DisplayName','SC-PF');
plot(t1:k,xh(1,t1:k),'-sr','DisplayName','PF');
plot(t1:k,xh(1,t1:k),'-sb','DisplayName','Truth')
legend(get(fig, 'Child'),'show')
legend('location','northwest')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM