[R] Getting discrete colors on plot
petr.pikal at precheza.cz
Fri Jan 18 08:09:30 CET 2013
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Mary
> Sent: Thursday, January 17, 2013 6:02 PM
> To: r-help at r-project.org
> Subject: Re: [R] Getting discrete colors on plot
> 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)
> # convert to long format
> mydata_long <- melt(mydata, id=c("id", "colorvar"))
> p <- ggplot(data=mydata_long,
> aes(x=variable, y=value,
> group=id, colour = colorvar)) +
> 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.
Learn to use factors.
'data.frame': 5 obs. of 7 variables:
$ id : num 1 2 3 4 5
$ x1 : num 5 2 3 5 1
$ x2 : num 4 1 3 5 1
$ x3 : num 5 2 3 5 1
$ x4 : num 4 3 3 5 1
$ x5 : num 3 1 3 5 1
$ colorvar: num 3 1 2 3 1
Your colorvar is numeric therefore the scale. If you want to make it discrete change it to factor.
and use your function to see the difference.
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help