[R] ggplot2 Y axis labels

Felipe Carrillo mazatlanmexico at yahoo.com
Wed Feb 18 23:21:36 CET 2009


Hi all:
Using the example below, is there a way to add Y axis titles to each graphic instead of sharing the same title?

library(ggplot2)

RT = matrix(c(814, 500, 424, 394, 967, 574, 472, 446),4,2)
colnames(RT) = c('repetition','alternation')
rownames(RT) = c('7-yrs','11-yrs','15-yrs','21-yrs')

rt <- melt(RT)
names(rt) <- c("age", "trt", "value")
rt$variable <- "rt"

#this next block was missing in Hadley's previous example
error = matrix(c(10,6,6,4,13,7,6,3),4,2)
colnames(error) = c('repetition','alternation')
rownames(error) = c('7-yrs','11-yrs','15-yrs','21-yrs')

errors <- melt(error)
names(errors) <- c("age", "trt", "value")
errors$variable <- "error"

df <- rbind(rt, errors)

# Make sure factors are ordered correctly
df$age <- factor(df$age, levels = c("7-yrs", "11-yrs", "15-yrs", "21-yrs"))

# Which results in:
structure(list(age = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("7-yrs", "11-yrs",
"15-yrs", "21-yrs"), class = "factor"), trt = structure(c(2L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label =
c("alternation",
"repetition"), class = "factor"), value = c(814, 500, 424, 394,
967, 574, 472, 446, 10, 6, 6, 4, 13, 7, 6, 3), variable = c("rt",
"rt", "rt", "rt", "rt", "rt", "rt", "rt", "error", "error", "error",
"error", "error", "error", "error", "error")), .Names = c("age",
"trt", "value", "variable"), row.names = c(NA, 16L), class = "data.frame")

# It's now straightforward to create recreate the plot with lines
# or with bars:

plot <- ggplot(df, aes(x=age, y=value, colour = trt, fill = trt)) +
facet_grid(variable ~ . , scale = "free")
plot + geom_bar(position = "dodge")  +   geom_line(aes(group = trt)) + geom_point()

Felipe D. Carrillo  
Supervisory Fishery Biologist  
Department of the Interior  
US Fish & Wildlife Service  
California, USA



More information about the R-help mailing list