0

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
joran
  • 169,992
  • 32
  • 429
  • 468
user3262756
  • 649
  • 1
  • 9
  • 27

1 Answers1

1

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.

Community
  • 1
  • 1
bouncyball
  • 10,631
  • 19
  • 31