nit
nit

Reputation: 689

Setting the color for an individual data point

How can I set the colour for a single data point in a scatter plot in R?

I am using plot

Upvotes: 24

Views: 105347

Answers (3)

Dason
Dason

Reputation: 61983

Doing what you want to do through code is easy enough and others have given nice ways to do this. If, however, you would rather click on the points you want to change the color of you can do this by using 'identify' along with the 'points' command to replot over those points in a new color.

# Make some data
n <- 15
x <- rnorm(n)
y <- rnorm(n)

# Plot the data
plot(x,y)

# This lets you click on the points you want to change
# the color of.  Right click and select "stop" when
# you have clicked all the points you want
pnt <- identify(x, y, plot = F)

# This colors those points red
points(x[pnt], y[pnt], col = "red")

# identify beeps when you click.
# Adding the following line before the 'identify' line will disable that.
# options(locatorBell = FALSE)

Upvotes: 20

Jason Morgan
Jason Morgan

Reputation: 2330

To expand on @Dirk Eddelbuettel's answer, you can use any function for col in the call to plot. For instance, this colors the x==3 point red, leaving all others black:

x <- 1:5
plot(x, x, col=ifelse(x==3, "red", "black"))

example 1

Same goes for point character pch, character expansion cex, etc.

plot(x, x, col=ifelse(x==3, "red", "black"),
     pch=ifelse(x==3, 19, 1), cex=ifelse(x==3, 2, 1))

example 2

Upvotes: 39

Dirk is no longer here
Dirk is no longer here

Reputation: 368579

Use the col= argument which is vectorized so that eg in

 plot(1:5, 1:5, col=1:5)

you get five points in five different colors:

enter image description here

You can use the same logic to use just two or three colors among your data points. Understanding indexing is key in languages like R.

Upvotes: 13

Related Questions