anne w
anne w

Reputation: 75

How to give least-squares lines the same colour as the respective data set in the scatter plot via MATLAB?

I have 3 different datasets from which I made a scatter plot. Different datasets I coded in different colours.

My code looks like that:

clear all;
close all;

% my colormap
colormap = [0, 0, 0
            0.5, 0.5, 0.5
            0,   0.5, 0.5];

% x values of 3 different datasets
xvalues = [10 20 30; 35 65 95; 22 42 82];

% y values of 3 different datasets
yvalues = [1 2 3; 6 12 24; 2 4 8];

figure;
axis([0 90  0 30]);

% loop for each dataset
for i = 1:3

    x = xvalues(i,:);    
    y = yvalues(i,:);
    scatter(x,y, 60, colormap(i,:));   hold on;    

end

Now, I would like to add least-squares lines for each of the dataset in the colour of the respective data set.

I added at the end of the code:

% add least-squares lines to scatter plot
h = lsline;
set(h,'linewidth',2,'color',colormap(i,:));

This will add the least-squares lines - all of them with the same color.

How can I give each of the least-squares lines the colour used for the respective datasets in the scatter plot

1

Upvotes: 3

Views: 1894

Answers (1)

Suever
Suever

Reputation: 65460

lsline will return a vector of line objects if you have multiple plot objects on your axes. You will need to set the colors individually.

hlines = lsline;
for k = 1:numel(hlines)
    set(hlines(k), 'Color', colormap(k, :))
end

The way that you are doing it, you are setting all best-fit lines to be the color specified by colormap(3,:).

enter image description here

If you use standard plot objects rather than scatter (there is no benefit to scatter here since you are using a constant color and size), then lsline should match the color of your object automatically. It does not do this for scatter plots as the color for each datapoint typically varies.

figure;
axis([0 90  0 30]);

% loop for each dataset
for k = 1:3
    x = xvalues(k,:);    
    y = yvalues(k,:);
    plot(x, y, 'o', 'Color', colormap(k,:));
    hold on;    
end

lsline;

Upvotes: 1

Related Questions