[R] assign same legend colors than in the grouped data plot

R. Michael Weylandt michael.weylandt at gmail.com
Sun Feb 26 02:46:30 CET 2012


Your code isn't reproducible...(note the "legend ...." block -- that's
not code) and (if I had to guess) it looks like you are using
attach(). Don't do that...

What do you mean it doesn't work? You say something about plotting
lines, but your "working" code (the first block) doesn't do that...

If you want to use ggplot2, it's very easy to make this all work:
ggplot(d, aes(x = x, y = y, color = factor)) + geom_line()

And the documentation gives (many) examples on how to change the color
scale as desired.

Michael

On Tue, Feb 21, 2012 at 9:09 AM, agent dunham <crosspide at hotmail.com> wrote:
> Dear all,
>
> Thanks all of u for your help. Now I've another similar problem. I want to
> plot within the same plot, different lines, each one in a different color
> depending on the factor level. I've been able to do it like this, but if i
> try with rainbow colors it doesn't work. Can anybody help me with rainbow
> colors, or with colors that you choose, not the ones chosen by R.
>
>
> tmp1 <- lm(y  ~ x  + factor)
>
> plot(x, y, xlab = "x", ylab = "y", col =factor , bty='L')
> legend(locator(1), legend = c("level 1 factor",  "level 2 factor","level 3
> factor",  "level 4 factor","level 5 factor"), col =
> seq.int(nlevels(factor)), lty = 1)
> for (i in c("level 1","level 2","level 3","level 4","level 5")) {
>   J <- factor== i   ;  x1 <- x[J]   ;y1 <- tmp1$fitted[J]   ;Ord <-
> order(x1) ;
>  lines(x1[Ord], y1[Ord], col=factor[J])}
>
> What it doesn't work:
>
> ...
> plot(x,y, xlab = "x", ylab = "y", col=rainbow(nlevels(factor))[factor])
> legend ...
> for (i in c("level 1","level 2","level 3","level 4","level 5")) {
>   J <- factor== i   ;  x1 <- x[J]   ;y1 <- tmp1$fitted[J]   ;Ord <-
> order(x1) ;
>  lines(x1[Ord], y1[Ord], col=*rainbow*(nlevels(factor))[J])   }
>
> Find attached a sample of my data
> http://r.789695.n4.nabble.com/file/n4407112/dfexamp.dat dfexamp.dat
>
> Thanks in advance, show crosspide at hotmail.com as user at host.com
>
> --
> View this message in context: http://r.789695.n4.nabble.com/assign-same-legend-colors-than-in-the-grouped-data-plot-tp4390641p4407112.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.



More information about the R-help mailing list