在ggplot中使用if else会抛出未找到的对象

时间:2017-11-22 15:07:32

标签: r ggplot2

在stat_bin中的if else循环中使用dataframe列时,即使数据框和列存在,也会抛出找不到的对象。这是一个可重现的代码

ggplot(mpg, aes(x = displ, fill = trans, label = trans)) +
  geom_histogram(binwidth = 1,col="black") +
  stat_bin(binwidth=1, geom="text", position=position_stack(vjust=0.5), aes(label=ifelse(..count..>4, as.character(trans), "")))

以上代码抛出以下错误

*Error in ifelse(count > 4, as.character(trans), "") : object 'trans' not found*

我甚至尝试过没有运气

ggplot(mpg, aes(x = displ, fill = trans, label = trans)) +
geom_histogram(binwidth = 1,col="black") +
stat_bin(binwidth=1, geom="text", position=position_stack(vjust=0.5), aes(label=ifelse(..count..>4, mpg$trans, "")))

我收到以下错误

 *Error in ifelse(count > 4, mpg$trans, "") : object 'mpg' not found*

当我拿出if else并尝试关注时,它工作正常(它检测数据帧和列名)

ggplot(mpg, aes(x = displ, fill = trans, label = trans)) +
geom_histogram(binwidth = 1,col="black") +
stat_bin(binwidth=1, geom="text", position=position_stack(vjust=0.5), aes(label=as.character(trans)))

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

由于ggplot2目前存在局限性(另请参阅我对您的问题的评论),您必须预先计算直方图以实现您想要做的事情。像这样:

breaks <- 1:7 + .5
mids <- 2:7
mpg %>% group_by(trans) %>%
  do(hist = data.frame(count = hist(.$displ, breaks = breaks, plot = FALSE)$counts,
                       displ = mids)) %>%
  unnest() %>%
  ggplot(aes(x = displ, y = count, fill = trans)) +
  geom_col(position = position_stack(vjust = 0.5), width = 1, color = "black") +
  geom_text(aes(label = ifelse(count > 4, trans, "")), position = position_stack(vjust = 0.5))

enter image description here