【问题标题】:ggplot geom_text not seating on top of barsggplot geom_text 没有坐在酒吧的顶部
【发布时间】:2016-02-27 09:49:16
【问题描述】:

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

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

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

这就是它的样子:

【问题讨论】:

    标签: r ggplot2 geom-bar geom-text


    【解决方案1】:

    一些建议,

    1. 使用lubridate 处理日期
    2. 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-19
      • 2021-03-18
      • 2014-01-10
      • 2015-05-18
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多