Reputation: 679
I'd like to label using a function but I get an error. Many thanks in advance for your input!
library(ggplot2)
drink <- c(replicate(18, "Water"),
replicate(22, "Beer"),
replicate(20, "Coke"))
person <- c(replicate(6, c(replicate(5, 1), replicate(5, 2))))
dd <- data.frame(person, drink)
rm(drink, person)
mf_labeller <- function(var, value){
value <- as.character(value)
if(var == "person"){
value[value == "1"] <- "Women"
value[value == "2"] <- "Men"
}
return(value)
}
p <- ggplot(dd,
aes(drink)) +
geom_bar(stat = "count") +
facet_grid(person ~ .,
labeller = mf_labeller)
p
Upvotes: 0
Views: 114
Reputation: 10761
Perhaps there's an easier way to do this, rather than using a function:
person_values <- c("1" = "Women",
"2" = "Men")
ggplot(dd, aes(drink)) +
geom_bar(stat = "count") +
facet_grid(person ~ ., labeller = as_labeller(person_values))
Equivalently, from the labeller
documentation:
ggplot(dd, aes(drink)) +
geom_bar(stat = "count") +
facet_grid(person ~ ., labeller = labeller(person = person_values))
Note that this solution comes from a previously asked question.
Upvotes: 1