Clear Filters
Clear Filters

How to combine scatter 'Marker' with lsline 'LineStyle' for a single entry in the Legend?

7 views (last 30 days)
I would like to create a plot of multiple scattered data, then add a (linear) fit to it. This is easily done with lsline() . The problem is I want to have one legend entry per data set, that would include the 'Marker' of the scattered set-of-points with the 'LineStyle' (and possibly 'color', though I can definitely do without it) of the respective lsline linear fit. I want the legend to look as if I had a 'LineStyle', '-' when plotting the scattered points, except that the continuous line would be the linear fit, rather than the line connecting the points. I am aware I can include only the scattered datasets in my legend, as mentioned in https://stackoverflow.com/questions/16145733/how-to-add-selective-datasets-for-legends, but as mentioned above this isn't what I'm looking for, since the legend doesn't include the LineStyle.
Code adapted from doc('lsline')
Thank you
x = 1:10;
rng default; % For reproducibility
figure;
% Create 3 scattered sets on the same figure
y1 = x + randn(1,10);
scatter(x,y1,25,'b','*')
hold on
y2 = 2*x + randn(1,10);
plot(x,y2,'mo')
y3 = 3*x + randn(1,10);
plot(x,y3,'rx:')
legend('1st', '2nd', '3rd', 'location', 'northwest'); % Add legend
h_lsline = lsline; % Add least square linear fit
  1 Comment
Udit Pant
Udit Pant on 16 Jun 2020
Hi,
One way of combining markers and line styles is to plot empty data (nan) for the desired style and then adding the plot handle for empty data to the legend. The 'AutoUpdate' option prevents the entries to be added automatically by the 'lsline' function.
x = 1:10;
rng default; % For reproducibility
figure;
% Create 3 scattered sets on the same figure
y1 = x + randn(1,10);
p1 = scatter(x,y1,25,'b','*');
hold on
y2 = 2*x + randn(1,10);
p2 = plot(x,y2,'mo');
y3 = 3*x + randn(1,10);
p3 = plot(x,y3,'rx:');
ph1 = plot(nan, nan, 'b-*', 'MarkerEdgeColor', 'b', 'DisplayName','1st');
ph2 = plot(nan, nan, 'm-o', 'MarkerEdgeColor', 'm', 'DisplayName','2nd');
ph3 = plot(nan, nan, 'r-x', 'MarkerEdgeColor', 'r', 'DisplayName','3rd');
legend([ph1, ph2, ph3], 'location', 'northwest', 'AutoUpdate','off'); % Add legend
h_lsline = lsline; % Add least square linear fit
Hope this helps.

Sign in to comment.

Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!