Search code examples
matlabplotlinesscatter

Scatter plot with coloured groups and different markers within a group


I am trying to make kind of a scatter plot with different groups. In addition to this I would like to have 2 different markers and one color for each set of 2 points, which are also connected with a line. But see below for details

I have 4 matrices

Db = [0.4745 0.3886 0.3316 0.2742; 0.5195 0.3825 0.3341 0.2846; 0.4929 0.3951 0.3161 0.2918; 0.4905 0.4052 0.3240 0.2882];
Dw = [0.4814 0.3905 0.3418 0.2922; 0.5258 0.3952 0.3420 0.2974; 0.4945 0.4012 0.3386 0.3001; 0.4885 0.4076 0.3382 0.3056];
Sb = [0.0476 0.0527 0.0543 0.0592; 0.0432 0.0503 0.0521 0.0592; 0.0460 0.0531 0.0536 0.0508; 0.0488 0.0520 0.0542 0.0543];
Sw = [0.0693 0.0738 0.0785 0.0839; 0.0642 0.0731 0.0763 0.0862; 0.0670 0.0755 0.0807 0.0753; 0.0744 0.0733 0.0792 0.0776];

I would like to plot them as a scatter plot with Sb against Db and Sw against Dw. But now I would like them to have different markers so that the Sb/Db points have an 'x' and Sw/Dw points have an 'o'.

Basically I would like to have the lower bunch of points as 'x' and the upper ones as 'o'

Then additionally I want to connect them with a line, so for example the first element of Sb/Db should be connected with the first element of Sw/Dw.

Something like this (edited in a graphics editor for this example...)

connect points with lines

I have tried with gscatter

gscatter([Db(:)' Dw(:)'],[Sb(:)' Sw(:)'],[1:16 1:16])

But with this I don't know how to change the markers or add lines.

Can someone help me with this?


Solution

  • You can do this with a couple of calls to scatter and one call to line.

    % Turn your data into 1D row vectors
    vDb = Db(:).'; vDw = Dw(:).'; vSb = Sb(:).'; vSw = Sw(:).';
    % Plotting
    figure; hold on
    % Scatters for points
    scatter(vDb, vSb, 'kx'); % plotting with black (k) crosses (x)
    scatter(vDw, vSw, 'ko'); % plotting with black (k) circles (o)
    % Line to get lines!
    line([vDb; vDw], [vSb; vSw], 'color', 'k') % Plot black (k) lines between 'b' and 'w' pts 
    

    Output:

    plot


    You can get different colours per pair by just using multiple calls to line instead of using scatter, specifying the markers for two of the calls but only using the start/end points, replacing the other with NaN.

    % No need for 'hold on' as line doesn't clear the plot!
    figure;
    line([vDb; NaN.*vDw], [vSb; NaN.*vSw], 'marker', 'x') % Plot coloured x markers
    line([NaN.*vDb; vDw], [NaN.*vSb; vSw], 'marker', 'o') % Plot coloured o markers
    line([vDb; vDw], [vSb; vSw]) % Plot coloured lines between 'b' and 'w' pts
    

    Output:

    plot2

    Note that this uses the default colour set. This can be changed by using

    set(gca, 'colororder', mycolours)
    

    where mycolours is a 3 column RGB matrix, as seen if you use get(gca, 'colororder').