user3262756 user3262756 - 3 months ago 12
R Question

"value missing" with facet labeller function

I'd like to label using a function but I get an error. Many thanks in advance for your input!

1_Load packages



library(ggplot2)


2_Dataframe



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)


3_Labeller function



mf_labeller <- function(var, value){
value <- as.character(value)
if(var == "person"){
value[value == "1"] <- "Women"
value[value == "2"] <- "Men"
}
return(value)
}


4_Labelled plot (Error appears here!)



p <- ggplot(dd,
aes(drink)) +
geom_bar(stat = "count") +
facet_grid(person ~ .,
labeller = mf_labeller)
p

Answer

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.