How can I set the colour for a single data point in a scatter plot in R
?
I am using plot
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"))
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))
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:
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.
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)