Changing line colors with ggplot()

RGgplot2

R Problem Overview


I don't use ggplot2 that much, but today I thought I'd give it a go on some graphs. But I can't figure out how to manually control colors in geom_line()

I'm sure I'm overlooking something simple, but here's my test code:

x <- c(1:20, 1:20)
variable <- c(rep("y1", 20), rep("y2", 20) )
value <- c(rnorm(20), rnorm(20,.5) )

df <- data.frame(x, variable, value )

d <- ggplot(df, aes(x=x, y=value, group=variable, colour=variable ) ) + 
            geom_line(size=2)
d

which gives me the expected output:

enter image description here

I thought all I had to do was something simple like:

d +  scale_fill_manual(values=c("#CC6666", "#9999CC"))

But that changes nothing. What am I missing?

R Solutions


Solution 1 - R

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Solution 2 - R

Here's a minimal reproducible example of another way to change line colours (try running it):

library(tidyverse)
library(ggplot2)

iris %>% 
  ggplot(aes(x = Petal.Length)) +
  geom_line(aes(y = Sepal.Length), color = "green") +
  geom_line(aes(y = Sepal.Width), color = "blue") 

enter image description here

This way can be particularly useful when you added the lines manually.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD LongView Question on Stackoverflow
Solution 1 - RIstaView Answer on Stackoverflow
Solution 2 - RstevecView Answer on Stackoverflow