Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign colors using a variable containing color names in a grouped ggplot?

Tags:

r

ggplot2

In this simple example, I create a variable with the names of colors.

df <- mtcars %>%
  mutate(color = "green",
     color = replace(color, cyl==6, "blue"),
     color = replace(color, cyl==8, "red"))

Running the code below works as expected.

ggplot(df, aes(wt, mpg)) +
  geom_point(color = df$color)

enter image description here

What if I want to use geom_line to create three lines--green, blue, and red?

ggplot(df, aes(wt, mpg, group=cyl)) +
  geom_line(color = df$color)

Instead, I get three lines with the colors cycling throughout. enter image description here

How can I use a variable with color names to assign the color of different lines?

like image 280
John J. Avatar asked Sep 03 '25 15:09

John J.


1 Answers

I think you are looking for scale_color_identity

ggplot(df, aes(wt, mpg)) +
  geom_point(aes(color = color)) +
  scale_color_identity(guide = "legend") # default is guide = "none"

enter image description here

Here is the respective line plot

ggplot(df, aes(wt, mpg)) +
  geom_line(aes(color = color)) +
  scale_color_identity(guide = "legend")

enter image description here

like image 113
markus Avatar answered Sep 05 '25 07:09

markus