Erica
Erica

Reputation: 105

Scatter Plot with Conditions in Matlab

I have a data set of particles.

Column 1 is the charge of the particle, Column 2 is the x coordinate, and Column 3 is the y coordinate.

I have renamed column 1 c_particles, column 2 x_particles, and column 3 y_particles.

I need to do a scatter plot of x vs y, but when the charge is positive the marker must be red, and when the charge is negative the marker must be blue.

So far I have

if c_particles < 0
scatter(x_particles,y_particles,5,[0 0 1], 'filled')
else
scatter(x_particles,y_particles,5,[1 0 0], 'filled')
end

which is yielding the plot, but the markers are all red.

Upvotes: 1

Views: 2036

Answers (1)

Brian L
Brian L

Reputation: 3251

Your first line isn't doing what you think it is:

c_particles < 0

will return a vector of booleans of the same length as c_particles; if will treat this array as true as long as at least one element is true. Instead, you can use this 'logical array' to index the particles you want to plot. I would try this:

i_negative = (c_particles < 0);       % logical index of negative particles
i_positive = ~i_negative;             % invert to get positive particles
x_negative = x_particles(i_negative); % select x-coords of negative particles
x_positive = x_particles(i_positive); % select x-coords of positive particles
y_negative = y_particles(i_negative);
y_positive = y_particles(i_positive);

scatter(x_negative, y_negative, 5, [0 0 1], 'filled');
hold on; % do the next plot overlaid on the current plot
scatter(x_positive, y_positive, 5, [1 0 0], 'filled');

Upvotes: 3

Related Questions