Obtain seperate legend for each contour line

53 views (last 30 days)
Hello everyone
%% sin(t)-(1/(1.5*V));
figure
[t,V]=meshgrid(-5:0.33:5,-5:0.3:5);
slope=sin(t)-(V./1.5);
length=sqrt(1+slope.^2);
quiver(t,V,1./length,slope./length,0.79);
xlabel('t in s')
ylabel('V(t)')
box on
title('slope field equation (2)')
legend('slope field')
yticks([-5:5:5]);
xticks([-6:2:6]);
axis([-6 6 -5 5])
hold on
c=[-2:1:2];
[C,h]=contour('v6',t,V,slope,c);
Here is my code but it displays the legend as in figure 1. I want the legend to be like in figure 2.
The legend in fi1 is placed in data1. I don't want to do it like that. I want every line to have its own legend
UPDATE!!!!!!!!!!!!!!!!: found the solution here
https://de.mathworks.com/matlabcentral/answers/284500-contour-plot-legend-how-to-change-symbol-to-straight-line

Accepted Answer

dpb
dpb on 3 Dec 2020
There's no way to make legend use the contour lines directly; there are not any object handles to them; and the legend is global to the object as you observe.
Again, one has to revert to subterfuge --
...
hQ=quiver(t,V,1./length,slope./length,0.79); % save handle
...
[C,hC]=contour('v6',t,V,slope,c); % identify handle
i1=2:C(2,1)+1:size(C,2); % retrieve beginning of contour lines
clr={'r','o','m','g','c'}; % define some colors -- not very distinct, could do better
hL=arrayfun(@(i,c) plot(C(1,i:i+60),C(2,i:i+60), ...
['-' c{:}],'DisplayName',num2str(C(1,i-1),'incline %d V/s')),i1,clr); % draw the contour lines
hLg=legend([hQ hL]); % legend for only objects wanted
produced:
Would seem worthy of enhancement request to contour altho I have serious doubts would ever be addressed...they think you're supposed to label the contour lines themselves instead.
  1 Comment
Mehdi Jaiem
Mehdi Jaiem on 3 Dec 2020
Edited: Mehdi Jaiem on 3 Dec 2020
Smart ! although it took me some time to understand it but the idea is good
I also found a dummy way to plot the legend .. hang on .. it's not that perfect idea but it did the job.
Simply ploted empty graphs and assigned a legend to them.
[t,V]=meshgrid(-5:0.35:5,-5:0.35:5);
slope=1-V-t;
length=sqrt(1+slope.^2);
hQ=quiver(t,V,1./length,slope./length,0.75);
xlabel('t in s')
ylabel('V(t)')
box on
title('slope field equation (1) ')
yticks([-5:5:5]);
xticks([-6:2:6]);
axis([-6 6 -5 5])
hold on;
c=[-2,-1,0,1,2];
[C,h]=contour(t,V,slope,c);
hm2 = plot(NaN);
hm1 = plot(NaN);
h0 = plot(NaN);
h1 = plot(NaN);
h2 = plot(NaN);
legend([hQ hm2 hm1 h0 h1 h2],'slope field','isocline -2 V/s', 'isocline -1 V/s','isocline 0 V/s','isocline 1 V/s','isocline 2 V/s');

Sign in to comment.

More Answers (0)

Categories

Find more on Contour Plots in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!