[R] Getting discrete colors on plot

Mary mlhoward at avalon.net
Thu Jan 17 18:02:15 CET 2013


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.


More information about the R-help mailing list