Home > Software engineering >  manually scale color of a factor in ggplot
manually scale color of a factor in ggplot

Time:12-02

Let's say i have a data frame like this

id password   year     length    Something
1 1234567      2001     7         good
2 pass4      2001       5         bad
3 angel3     2003       6         bad
4 pizza      2004       5         ok

im trying to get a code that would create a geom_point with 3 variable but i only want to highlight a single level of the factor ''Something'' . And i dont want any of the other levels of the factor Something(like good or bad) to colored. Or at least they can stay black.

im was thinking maybe something like this :

graph <- dat %>% 
        ggplot(aes(x=(year), y=length, color=Something$ok) 
      geom_point()

but i can't use $ .

CodePudding user response:

You can color just one point by setting all points to one color and changing the color of the point you want to change. To do this you can use scale_color_manual

Data:

dat <- structure(list(id = 1:4, password = structure(c(1L, 3L, 2L, 4L
), .Label = c("1234567", "angel3", "pass4", "pizza"), class = "factor"), 
    year = c(2001L, 2001L, 2003L, 2004L), length = c(7L, 5L, 
    6L, 5L), Something = structure(c(2L, 1L, 1L, 3L), .Label = c("bad", 
    "good", "ok"), class = "factor")), class = "data.frame", row.names = c(NA, 
-4L))

Plot:

dat %>% 
  ggplot(aes(x=(year), y=length, color = Something == "ok")) 
  geom_point()  
  scale_color_manual(values = c("blue", "orange"))

example

  • Related