使用facet贴标机功能“缺少值”

时间:2016-08-11 12:06:15

标签: r function ggplot2 facet

我想使用函数标记,但是我收到错误。非常感谢您的投入!

1_Load包

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功能

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(此处出现错误!)

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

1 个答案:

答案 0 :(得分:1)

也许有一种更简单的方法,而不是使用函数:

person_values <- c("1" = "Women",
                   "2" = "Men")

ggplot(dd, aes(drink)) +
    geom_bar(stat = "count") +
    facet_grid(person ~ ., labeller = as_labeller(person_values))

等同于labeller文档:

ggplot(dd, aes(drink)) +
    geom_bar(stat = "count") +
    facet_grid(person ~ ., labeller = labeller(person = person_values))

请注意,此解决方案来自a previously asked question