[R] Getting discrete colors on plot

Jim Lemon jim at bitwrit.com.au
Fri Jan 18 07:30:31 CET 2013


On 01/18/2013 04:02 AM, Mary wrote:
> Hi,
>
> This is my first post; I'm new to R but am a senior statistical programmer.  I have done a lot of graphs using SAS Graph but now am trying to transition to using graphs in R.
>
> I'm trying to produce a graph where the colors have three categories- ideally I would like them to be Green for good, Yellow for Questionable, and Red for bad.
>
> So I tried to do this in GGPLOT; here is my code:
>
> id<-       c(1,2,3,4,5)
> x1<-       c(5,2,3,5,1)
> x2<-       c(4,1,3,5,1)
> x3<-       c(5,2,3,5,1)
> x4<-       c(4,3,3,5,1)
> x5<-       c(3,1,3,5,1)
> colorvar<- c(3,1,2,3,1)
>
> mydata<- data.frame(id,x1,x2,x3,x4,x5,colorvar)
> head(mydata)
>
> # convert to long format
> require("reshape")
> mydata_long<- melt(mydata, id=c("id", "colorvar"))
> head(mydata_long)
>
> require("ggplot2")
> p<- ggplot(data=mydata_long,
>         aes(x=variable, y=value,
> group=id, colour = colorvar)) +
>      geom_line()
> p
>
>
> This works, but I get more colors on the graph than my colorvar has.  I have 3 colors on my colorvar, but 5 colors show up on the graph, including 1.5 and 2.5.   How do I tell ggplot only to use the 3 colors and not give me a gradient of colors?  Also how would I specify the colors that I want, such as the RGB equivalents of green, yellow, and red?  My real data will have many more records.
>
> -Mary
>
Hi Mary,
I'm not exactly sure what you are doing with the "melt" function, but does:

matplot(mydata$id,mydata[,2:6],col=mydata$colorvar+1,type="l")

give you something like what you want?

Jim



More information about the R-help mailing list