Friday, 13 September 2013

Ordering levels of a factor in ggplot2

Ordering levels of a factor in ggplot2

Is it possible to plot the following data by a given rank and to specify
this rank in geom_plot? Or should I order the factor before. I mean, I
want to plot the ids in the following order B, A, C, where B is dark blue
and C is light blue.
tim.seq <- seq(as.POSIXlt("2013-07-01 00:00:00", origin="1960-01-01",
tz="GMT"),
as.POSIXlt("2013-07-8 00:00:00", origin="1960-01-01",
tz="GMT"),
by="1 hour")
id <- factor(sample(LETTERS[1:3], length(tim.seq), T, prob=c(0.4,0.8,0.2)))
rank <- factor(id, levels=levels(id), label=c(2,3,1))
data <- data.frame(time=tim.seq, id=id, rank=rank)
p1 <- ggplot(data, aes(x=time, y=..count.., alpha=id))
p1 <- p1+ geom_bar(fill="darkblue", binwidth=60*60*24, position="identity")
p1 <- p1+ scale_alpha_discrete(range=c(1, 0.2))
p1

No comments:

Post a Comment