Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.



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 nonfilled 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 ith cont. end
cl2=sort(unique(cont_level),'descend'); % find unique cont levels cl2=cl2(1:end1); % 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)



