0
votes

I seem to be having problems creating a 2D scatter plot in matlab with two grouping variables which displays different colors for one of them and different markers for the other. The variable "score" has the X and Y values and the two grouping variables are "att21" and "att22".

I use the following code:

f=figure;
gscatter(score(:,1), score(:,2), {att21, att22}, 'br', 'xo');

what I'm getting is: scatter plot

However, what I want to get is blue for L4 and red for L1 and x for Flake and o for Chunk. I would also like the legend to indicate this.

What am I missing?

Thanks for any help...

2

2 Answers

0
votes

OK, I think I figured it out. The solution provided by Noel is good only if I know the number of groups in each grouping variable, but unfortunately this is not the case.

So I came up with the solution if using nested loops.

f=figure;
hold on;
marker = '+o*.xsd';
clr = 'rgbymck';

att1v = unique(att1);
att2v = unique(att2);
attv = [att1v; att2v];
att1count = 1;
att2count = 1;

for k=1:length(score)
    att1count = 1;
    att2count = 1;
    while att1count <= length(att1v)
        if isequal(att1(k),att1v(att1count))
            while att2count <= length(att2v)
                if isequal(att2(k),att2v(att2count))
                    f=scatter(score(k,1),score(k,2),15,clr(att1count),marker(att2count));

                end
                att2count = att2count + 1;
            end
        end
        att1count = att1count + 1;
    end
end
legend(attv);

Now the scatter plot is OK and its supports up to 7 groups in each variable. The only problem I'm left with is that I can't manage to create a Legend which shows the different labels for all the groups.

All I manage to get is this:plot with bad legend

If anyone has a solution for me it will be great...

Thanks alot

0
votes

When you are grouping by 2 grouping variables, each with 2 categories, you are implicitly creating 4 different groups, so you have to define the color and markers for the 4 groups, in your case

gscatter(score(:,1), score(:,2), {att21, att22}, 'rrbb', 'xoxo');

But since gscatter will repeat the pattern if the defined color or marker is smaller than the number of groups, you can save 2 characters by doing

gscatter(score(:,1), score(:,2), {att21, att22}, 'rrbb', 'xo');

If you don't know the number of groups in each category, you can obtain them with the command unique and count them, and then use that number to create the markers and colors. For your example

marker = '+o*.xsd';
clr = 'rgbymck';

n_groups_att1 = length(unique(att21));
n_groups_att2 = length(unique(att22));

m = marker(1:n_groups_att2);

c = repmat(clr(1:n_groups_att1),n_groups_att2,1);
c = c(:)';

gscatter(score(:,1), score(:,2), {att21, att22}, c, m);

Just make sure that marker and clr has more elements than possible number of groups in each grouping variable