MATLAB: Problem displaying labels in legend – fit curve overwrites data labels

curve fittinglegendMATLAB

Hi,
I thought this would be a simple issue but can't figure it out: I want to create a graph of data which also displays a fit curve. The legend should display the value of the variable corresponding to the slope of the fit line.
This code produces a plot of the graph with the legend label appearing correctly:
x=load('diffusionall_x.xmgr');
[ppx,errx]=fit(x(:,1),x(:,2),'poly1');
slopex=ppx.p1
plot2=plot(x(:,1),x(:,2),'b','DisplayName',num2str(slopex))
legend('show')
But when I add a plot of the fit line, the legend label for plot1 is no longer displayed and instead only the default "fitted curve" label for plot 1 is displayed in the legend:
x=load('diffusionall_x.xmgr');
[ppx,errx]=fit(x(:,1),x(:,2),'poly1');
slopex=ppx.p1
plot2=plot(x(:,1),x(:,2),'b','DisplayName',num2str(slopex))
hold on
plot1=plot(ppx,'r-')
legend('show')
I have tried many options to avoid displaying the plot1 "fitted curve" label:
plot1=plot(ppx,'r-', 'DisplayName',num2str(slopex))
plot1=plot(ppx,'r-', ,'HandleVisibility','off')
set(get(get(plot1,'Annotation'),'LegendInformation'),'IconDisplayStyle','off')
None of them work. Even when I set the IconDisplayStyle to 'off', plot 1 legend label still displays and the plot2 label disappears. On the other hand, attempting to set the 'DisplayName' or 'HandleVisibility' property of plot1 produces a lengthy error message:
Warning: The method char/diff will be removed in a future
release. Use sym/diff instead. For example diff(sym('x^2')).
After removal diff('x^2') will return diff(double('x^2')).
> In char.diff at 10
In cfit.plot at 65
In test at 9
??? Error using ==> sym.sym>notimplemented at 2621
Function 'lt' is not implemented for MuPAD symbolic objects.
Error in ==> sym.sym>sym.lt at 812
notimplemented('lt');
Error in ==> cfit.plot at 65
if any(diff(xdata)<0)
Error in ==> test at 9
plot1=plot(ppx,'r-', 'DisplayName',num2str(slopex))
Can anyone help me plot both the data and the fit curve and display only the label for the data but not the fit curve? Or alternatively, tell me how to modify the label displayed for the fit curve seeing that 'DisplayName' cannot be set?
Thanks! Pawel

Best Answer

You can call the legend command with the first argument being the exact object handles that you want to include in the legend. Here is a simple example. Does this help?
x = 1:10;
figure
hold on
h1 = plot(x,x+1,'r'); % First line
h2 = plot(x,x+2,'g'); % Second line
h3 = plot(x,x+3,'b'); % Third line
legend([h1 h3],{'First line','Third line'}) % Legend for only two lines