Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Legend for Contour Plot
Replies: 5   Last Post: Apr 9, 2014 6:04 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Jessica Piper

Posts: 5
Registered: 2/17/11
Re: Legend for Contour Plot
Posted: Sep 22, 2013 7:38 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

Claude, thank you for your elegant solution. (Though, using i or j as a variable in for loops is actually bad practice in Matlab, since it messes up imaginary numbers.) I modified your code to sort the labels and eliminate duplicates. The code below works with both contour and contourf, and should be essentially equivalent to clegendm from the mapping toolbox, which really should be included in Matlab as a matter of course! (Mathworks, please act on this hint!)

Npeak=80; Nlevels=8;
z = peaks(Npeak);
[~,hc2] = contourf(z,Nlevels); % generate contours
%(just replace contourf with contour for the non-filled case)

hcont = get(hc2,'children'); % get vector of contour handles
cont_level=zeros(size(hcont));
for ii = 1:length(hcont)
cont_level(ii) = get(hcont(ii),'userdata'); % level of i-th cont.
end

cl2=sort(unique(cont_level),'descend'); % find unique cont levels
cl2=cl2(1:end-1); % exclude last value which tends to not exist in plot
hc2=zeros(size(cl2)); legend_entries=cell(size(cl2));
for ii=1:length(cl2) % find unique handle list & make corresponding legend
hc2(ii)=hcont(find(cont_level==cl2(ii),1));
legend_entries{ii} = num2str(cl2(ii));
end
legend(hc2,legend_entries)



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.