# [R] Getting discrete colors on plot

arun smartpink111 at yahoo.com
Fri Jan 18 04:03:12 CET 2013

```HI,

May be this helps:
mydata_long1<-within(mydata_long,{colorvar<-factor(colorvar,levels=1:3)})
require("ggplot2")
p <- ggplot(data=mydata_long1,
aes(x=variable, y=value,
group=id, colour = colorvar)) +
geom_line()
p

A.K.

----- Original Message -----
From: Mary <mlhoward at avalon.net>
To: r-help at r-project.org
Cc:
Sent: Thursday, January 17, 2013 12:02 PM
Subject: Re: [R] Getting discrete colors on plot

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)

# convert to long format
require("reshape")
mydata_long <- melt(mydata, id=c("id", "colorvar"))

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

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help