4

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?

John J.
  • 1,450
  • 1
  • 13
  • 28
  • Does this answer your question? [How to conditionally highlight points in ggplot2 facet plots - mapping color to column](https://stackoverflow.com/questions/15804504/how-to-conditionally-highlight-points-in-ggplot2-facet-plots-mapping-color-to) – tjebo Jul 01 '20 at 13:43

3 Answers3

5

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

markus
  • 25,843
  • 5
  • 39
  • 58
0

You can use a custom color scale:

ggplot(df, aes(wt, mpg, group=cyl)) +
    geom_line(aes(color = color)) +
    scale_color_manual(values = c("blue"="blue","red"="red","green"="green"))
Richard J. Acton
  • 885
  • 4
  • 17
-1

Short answer: you can't. You have set the variable to set the colors in the variable you created.

However, there is a way to do this in ggplot by default:

mtcars$cyl <-as.factor(mtcars$cyl) ## set mtcars$cyl as factors (i.e use exact values in column)

ggplot(mtcars, aes(x=wt, y= mpg, color = cyl)) +
       geom_point()+
       scale_color_manual(breaks = c("8", "6", "4"),
                    values=c("red", "blue", "green"))+ ## adjust these if you want different colors
       geom_line()

Left out the lines bit...

bob1
  • 398
  • 3
  • 12