Search All of the Math Forum:

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

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

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

 Messages: [ Previous | Next ]
 Jessica Piper Posts: 5 Registered: 2/17/11
Re: Legend for Contour Plot
Posted: Sep 22, 2013 7:38 PM

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)

Date Subject Author
6/2/07 Paul Brenner
6/3/07 Claude
9/22/13 Jessica Piper
4/9/14 Jonas
6/4/07 Matt Wolinsky
9/23/13 Açmae