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)
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.
How can I use a variable with color names to assign the color of different lines?
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"
Here is the respective line plot
ggplot(df, aes(wt, mpg)) +
geom_line(aes(color = color)) +
scale_color_identity(guide = "legend")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With