MATLAB: How to change the colour of certain indices in scatterplot

colourfigureforifscatterscatterplot

Hello, I am very new to this.
I am looking to make a scatter plot with some points plot as black point and some as red according to the indices.
I have a 19 elements array and for the values at indices 2, 4, 6, 9, 13, 15, 16 I want the point to be red and the other ones to be black.
Let A be my 19 elemets array
Let X be my X array
Let indice = [2 4 6 9 13 15 16]
I first wrote this:
scatter(X,A,'*k') and now how can I modify this to get the red points at the proper values?
I guess I need to do a if or for but I am not quite sure how do do this. Can anyone help me out?
Thanks

Best Answer

  • Here's are 4 demo that all achieve the same result.
    Xvals = [1,2,3,4,5,6,7,8,9];
    Yvals = [2,5,5,5,2,2,5,5,5];
    % Show scatter plot were all y-val greater than 3 are red
    % and all y-vals less than or equal to 3 are black.
    % METHOD 1
    cla()
    col = [0 0 0; 1 0 0]; % [black; red]


    isGreater = Yvals > 3;
    scatter(Xvals, Yvals, 50, col(isGreater+1,:), 'filled')
    % METHOD 2 (variation of method 1)
    cla()
    baseColors = [0 0 0; 1 0 0]; % [black; red]
    isGreater = Yvals > 3;
    cmap = baseColors(isGreater+1,:);
    scatter(Xvals, Yvals, 50, cmap, 'filled')
    % METHOD 3
    ax = cla();
    isGreater = Yvals > 3;
    scatter(Xvals, Yvals, 50, isGreater+1, 'filled')
    ax.Colormap = [0 0 0; 1 0 0]; % [black; red]
    % METHOD 4
    cla()
    hold on
    isGreater = Yvals > 3;
    scatter(Xvals(~isGreater), Yvals(~isGreater), 50, 'k', 'filled')
    scatter(Xvals(isGreater), Yvals(isGreater), 50, 'r', 'filled')