MATLAB graph plotting: assigning legend labels during plot

删除回忆录丶 提交于 2019-11-30 05:11:15
tmpearce

One option is to take advantage of the 'UserData' property like so:

figure;
hold on
plot([0 1], [1 0], '-b', 'userdata', 'blue line')
plot([1 0], [1 0], '--r', 'userdata', 'red dashes')

% legend(get(get(gca, 'children'), 'userdata'))                      % wrong
legend(get(gca, 'children'), get(get(gca, 'children'), 'userdata'))  % correct

Edit: As the questioner pointed out, the original version could get out of order. To fix this, specify which handle goes with which label (in the fixed version, it is in the correct order).

You should be able to set the DisplayName property for each plot:

figure
hold on
plot(...,'DisplayName','DataSet1')
plot(...,'DisplayName','DataSet2')
legend(gca,'show')

http://www.mathworks.com/help/matlab/ref/line_props.html

Side Note: I've found a lot of little tricks like this by getting the figure to look the way I want, then choosing the Figure's "File" menu option "Generate M-File..." and inspecting the generated output code.

willzone1

Use 'DisplayName' as a plot() property, and call your legend as

legend('-DynamicLegend');

My code looks like this:

x = 0:h:xmax;                                  %// get an array of x-values
y = someFunction;                              %// function
plot(x, y, 'DisplayName', 'Function plot 1');  %// plot with 'DisplayName' property

legend('-DynamicLegend',2);                    %// '-DynamicLegend' legend

Source: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/

You can try something like the following

for k = 1:10

   h(k) = plot(...);
   name{k} = ['condition ' num2str(k)];

end

legend(h, name);
Thomas van Dijk

Make a for loop. But Before the for loop, make an array.

%for example 

legendset = {}

for i = 1:10 

%blabla
%Then in the fore loop say: 

legendset = [legendset;namedata(i)]

%It puts all names in a column of legendset. 
%Make sure namedata are characters. 

%foreloop ends
end

%Then after the foreloop say: 

legend(legendset). 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!