2015-11-24 21 views
0

我有一些数据,有些组在所有月份都没有出现。我正在将其绘制在条形图上,但文本标签显示的是数字值,但文本并不位于每个条的顶部。我尝试使用标签的位置“闪避”,但没有成功。ggplot geom_text不能坐在酒吧的顶部

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

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 = "") ,''))) 

这是什么样子:

enter image description here

回答

1

一对夫妇的建议,

  1. 使用lubridate与日期
  2. 工作
  3. Months设置为因子变量。这将有助于使用position_dodge()

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

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)) 

enter image description here