overlaying scatter plots on the same graph to control marker color

Hi all,
I am trying to plot data from an excel file. Say I am plotting column 1 vs column 2 but want the marker colors to be blue or red depending on whether the corresponding value in column 3 is 1 or 0. I have written up some code to try to do this but all it does is plot the data with all the markers as blue.
massdata = xlsread('massdata.xlsx');
x = massdata(:,12);
y = massdata(:,15);
gamma = massdata(:,16);
for i = 1:1:32
if gamma(i) == 0
scatter(x, y, 'red');
hold on
end
if gamma(i) == 1
scatter(x, y, 'blue');
hold on
end
end
I am new to matlab so could somebody please let me know what I'm doing wrong? Or if there is an easier/better way to implement conditional marker coloring into a scatter plot.
Thanks very much, Colin

 Accepted Answer

You're checking column 16, not column 3! Try this:
% Create sample data
% massdata = randi(6, 32, 16)-1;
% massdata(:, 3) = randi(2, 32, 1)-1
x = massdata(:,12);
y = massdata(:,15);
gamma = massdata(:, 3);
itIs1 = gamma == 1;
% Plot it.
scatter(x(itIs1), y(itIs1), 20, 'r', 'LineWidth', 6);
hold on;
scatter(x(~itIs1), y(~itIs1), 20, 'b', 'LineWidth', 6);
grid on;

2 Comments

Hi Image, thanks again for the quick reply!
I had just said 3 for the sake of the explanation, 16 was the correct one. But your code worked perfectly, that is a useful syntax. The next step I need to do is incorporate another column of data that will control the marker shape of each data point, while keeping the colors you've just help me set up.
The data in this column has a range of 4 values so I will only need 4 shapes. I've tried to extrapolate your code to add more scatters in the way you had done the previous ones but it didn't do anything for me. Is it possible to do that this way? thanks
Yes it is. It's the same concept - multiple calls to scatter, except that you use the 'MarkerType' option to specify the marker type. Mark the Answer as accepted if that does the trick. Thanks.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!