[R] ggplot2 - Specifying Colors Manually

Hadley Wickham h.wickham at gmail.com
Wed Jul 22 22:04:31 CEST 2015


Try this:

ggplot(mydf,aes(x)) +
  geom_line(aes(y = y1, colour = "y1")) +
  geom_line(aes(y = y2, colour = "y2"))  +
  scale_color_manual(values = c(y1 = "green4", y2 = "blue2"))

Note that you don't need to use `mydf` and names in the manual scale
should match the values in the aes() calls.
Alsoit'smucheasiertoreadyourcodeifyouusespaces;)

Hadley

On Wed, Jul 22, 2015 at 1:13 PM, Abiram Srivatsa <avsrivatsa at gmail.com> wrote:
> Hi,
>
> Given a data frame, I'm trying to graph multiple lines on one graph, each
> line being a different color and each colored line corresponding to a
> specific name in the legend. Here is a very basic data sample to work with:
>
>  x <- seq(0,40,10)
>  y1 <- sample(1:50,5)
>  y2 <- sample(1:50,5)
>
>  mydf <- data.frame(x,y1,y2)
>
>  p <- ggplot(mydf,aes(x=mydf$x)) +
> geom_line(aes(y=mydf$y1,colour="green4")) +
> geom_line(aes(y=mydf$y2,colour="blue2"))  +
>
>  scale_color_manual(name="legend",values=c(y1="green4",y2="blue2"))
>
>
>  p
>
>
> When I run this, the entire plot is blank. What I WANT to show up is two
> lines, one being the color of green4 and the other being blue2. Besides
> that, I'm trying to associate the colors with the names "y1" and "y2" in
> the legend, but my codes don't seem to be working.
>
> I'm very new to R/ggplot2, and I really appreciate any and all help I can
> get.
>
> Thank you!
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
http://had.co.nz/



More information about the R-help mailing list