ggplot geom_text 不在栏的顶部

ggplot geom_text not seating on top of bars

我有一些数据,其中某些组不会出现在所有月份。我将其绘制在条形图上,但带有显示数值的文本标签,但文本并未位于每个条形图的顶部。我尝试使用位置 "dodge" 作为标签,但没有成功。

下面是一个可重现的例子:

library(ggplot2)
library(dplyr)
library(scales)

data.frame(Month = as.Date(c("2015-01-01", "2015-01-01","2015-01-01",
"2015-02-01","2015-02-01","2015-02-01")),
       types = rep(LETTERS[1:3],2),
       percent = c(0.2,NA,NA,.39,.89,.59)) %>%
  ggplot( aes(x = Month, y = percent, fill = types)) +  
  geom_bar(stat = "identity", position = "dodge") + 
  scale_y_continuous(labels = percent) +
  scale_x_date(labels = date_format("%Y-%b")) +
  geom_text(stat = 'identity', 
        aes(label = ifelse(percent > .02,
                           paste(round(percent*100,0),"%",sep = "") ,'')))

这是它的样子:

一些建议,

  1. 使用 lubridate 处理日期
  2. Months设置为因子变量。这在使用 position_dodge().
  3. 时会有帮助

尝试使用下面的代码。如果您有超过一年的数据,您可以考虑构建月份因子变量,并将年份附加到月份。

library(ggplot2)
library(dplyr)
library(scales)
library(lubridate)

data.frame(Month = months(ymd(c("2015-01-01", "2015-01-01","2015-01-01", "2015-02-01","2015-02-01","2015-02-01"))),
           types = rep(LETTERS[1:3],2),
           percent = c(0.2,NA,NA,.39,.89,.59)) %>%
  mutate(Month = factor(Month, levels = month.name),
         label = ifelse(!is.na(percent), paste0(round(percent*100), "%"), "")) %>% 
  ggplot() + 
  aes(x = Month, y = percent, fill = types) + 
  geom_bar(stat = "identity", position = position_dodge(w = 0.75)) + 
  geom_text(position = position_dodge(w = 0.75), 
            aes(ymax = percent, label = label))