# Marker and Line in legend in matlab plot

541 views (last 30 days)
Yogesh T L on 6 Apr 2016
Commented: Yogesh T L on 9 Apr 2016
Hi, I am plotting the experimental data and fitted line using matlab plot. The legend command shows the markers (data points) and line (fit) as a separate legend entry. However, I am interested to obtain the marker and line in a single legend entry so that the total number of legend entries could be reduced from 8 to 4 in my case. Hence, I would like to ask your assistance which could be useful for my plot. Thank you.

Walter Roberson on 6 Apr 2016
Create additional line objects that combine the attributes, such as
LH(1) = plot(nan, nan, '*-r');
LH(2) = plot(nan, nan, '^:g');
L{2} = 'cheese';
Then legend() those
legend(LH, L)

Yogesh T L on 6 Apr 2016
Hi Walter, Thank you for your response. However, I have the situation similar to Stevan as shown in the link for your kind reference http://se.mathworks.com/matlabcentral/answers/711#answer_1080. I also tried the accepted answer by Martijn but found some errors. Please let me know if you have any suggestions or comments.
Walter Roberson on 9 Apr 2016
Example:
x = 1 : 20;
y1 = sin(x);
plot(y1, 'r-');
hold on
plot(y1+randn(size(x)), 'r*');
y2 = tan(x.*(x-3).*(x-5));
plot(y2, 'b:');
plot(y2 .* rand(size(x)), 'b^');
LH(1) = plot(nan, nan, 'r-*');
LH(2) = plot(nan, nan, 'b:^');
L{2} = 'cheeses';
legend(LH, L);
hold off
Notice how the solid red line and the red * plot independently but there is a single red line with * in the legend. Likewise notice how the dotted blue line and the blue triangles plot independently but there is a single doted blue line with triangle in the legend.
Do not legend() the line handles that have the individual attributes. Instead, create some new lines that have the desired pair of attributes and legend() those new lines. Those new lines do not show up in the drawing because you set their data to nan and nan is never drawn on screen -- but not being drawn on screen does not mean they cannot have legend() applied to them.
Yogesh T L on 9 Apr 2016
Thank you Walter.