2

I would like to change the colour of a specific point in a dataframe, note that I am not plotting the condition.

library(ggplot2)
colpf <- c(0,0,0,1,1,1,2,2,2)
coldf <- c(0,1,2,0,1,2,0,1,2)
x <- seq(0,8,1)
y <- seq(0,8,1)
df <- data.frame(colpf,coldf,x,y)

ggplot(data = df) +
  geom_point(aes(x=x,y = y))

reproducible plot I would like to make the point which corresponds to colpf = 1 and coldf=1, say, red. In this case I believe it would be the point (4,4). I believe this will have a simple solution however my mind cannot seem to grasp it. Thank you.

Fish_Person
  • 107
  • 5

2 Answers2

3

Create an indicator variable telling if the condition is met. Map the color aesthetic to that variable and adjust the colors with a scale_* layer.

library(ggplot2)
colpf <- c(0,0,0,1,1,1,2,2,2)
coldf <- c(0,1,2,0,1,2,0,1,2)
x <- seq(0,8,1)
y <- seq(0,8,1)
df <- data.frame(colpf,coldf,x,y)

i <- with(df, colpf == 1 & coldf == 1)
i
#> [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

ggplot(data = df) +
  geom_point(aes(x = x, y = y, color = i), show.legend = FALSE) +
  scale_color_manual(values = c(`FALSE` = "black", `TRUE` = "red"))

Created on 2023-02-23 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1

Although Rui Barradas's answer is more elegant, if you didn't want to condition or could not determine a specific condition an alternative is to do this by indexing the specific point of interest:

ggplot() +
  geom_point(data = df[-5,], aes(x = x, y = y), show.legend = FALSE) +
  geom_point(data = df[5,], aes(x = x, y = y), color = "red", show.legend = FALSE)

enter image description here

jpsmith
  • 11,023
  • 5
  • 15
  • 36