Clear Filters
Clear Filters

Contour plot Legend | How to change symbol to straight line?

29 views (last 30 days)
Hi,
I am having trouble with the contour plot legend. I do not like the symbol used in the legend. I would like to remove the contour symbol and simply use a straight line for my legend symbol. Any ideas would be appreciated.
Here is the code I used to generate the plot.
figure();
box on
hold on
contour(R,P,regime1,[1,2],'b')
contour(R,P,regime2,[1,2],'r')
xlim([0,Rmax-2])
ylim([0,Pmax-2])
legend('series 1','series 2','Location','Best')

Accepted Answer

Matt Cohen
Matt Cohen on 18 May 2016
Hi EM,
I understand you are interested in modifying the legend in a contour plot to use straight lines instead of contour symbols.
Assuming you are using MATLAB R2014b or later, there are some possible workarounds that you can use for this. One way to create a legend containing the colors of the contours is to create invisible lines with the colors of the contour plots. You can either plot NaN values in the figure, which will not directly show up in the figure, or you can create a Line object and set its 'Visible' property to 'off'. The following example code shows how you can do both:
%%Create arrays
x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);
%%Plot NaN values
figure
hold on
contour(X,Y,Z,(-2:0.5:2),'Color','r');
hRed = plot(NaN, '-r');
contour(X,Y,Z*2,(-12:4:12)/3,'Color','b');
hBlue = plot(NaN, '-b');
legend([hRed hBlue], 'red', 'blue');
%%Lines with 'Visible' set to 'off'
figure
line(X(1:2),Y(1:2),'Color','r','Visible','off');
line(X(1:2),Y(1:2),'Color','b','Visible','off');
legend('red','blue');
hold on
contour(X,Y,Z,(-2:0.5:2),'Color','r');
contour(X,Y,Z*2,(-12:4:12)/3,'Color','b');
hold off
I hope this information proves to be helpful.
Matt

More Answers (0)

Community Treasure Hunt

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

Start Hunting!