【问题标题】:ggplot2 labels won't dodge with geom_col barsggplot2 标签不会与 geom_col 条一起闪避
【发布时间】:2020-10-09 16:36:03
【问题描述】:

我已经解决了相关问题,但这些答案并没有解决我的标签不躲避以匹配 geom_col 条的问题:

数据

x <- structure(
  list(capacity = c(0, 0, 0, 2.1, 3.1, 4, 4.6, 5.6, 6, 
                                 1.9, 2.3, 3.8),
       year = c("FY21", "FY21", "FY21", "FY21", "FY21",
                "FY20", "FY20", "FY20", "FY20", "FY19", "FY19", "FY19"),
       unified_date = structure(c(18536, 18567, 18597, 18628, 18659,
                                  18567, 18597, 18628, 18659, 18536,
                                  18567, 18597), class = "Date")),
  row.names = c(NA, -12L), class = c("tbl_df", "tbl", "data.frame"))                   

代码

ggplot2::ggplot(x, aes(x = unified_date, y = capacity, fill = year)) +
  geom_col(position = "dodge") +
  geom_text(aes(label = capacity),
            position = position_dodge(width = 1),
            vjust = -0.5, size = 4)

图表

我尝试将fill = year 添加到geom_text aesgroup = year,移动aes 值,position_dodge() 上的变体 - 没有。

【问题讨论】:

    标签: r ggplot2 geom-text


    【解决方案1】:

    试试这个:

    #Code
    ggplot2::ggplot(x, aes(x = factor(unified_date), y = capacity, fill = year)) +
      geom_bar(stat='identity',position = "dodge") +
      geom_text(aes(label = capacity),
                position=position_dodge(width=0.9), size = 4,vjust=-0.5)+
      xlab('Date')
    

    输出:

    如果您想正确处理月份,请尝试以下操作:

    #Code 2
    x %>% mutate(Month=format(unified_date,'%b')) %>%
      mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
      ggplot2::ggplot(aes(x = Month, y = capacity, fill = year)) +
      geom_bar(stat='identity',position = "dodge") +
      geom_text(aes(label = capacity),
                position=position_dodge(width=0.9), size = 4,vjust=-0.5)+
      xlab('Date')
    

    输出:

    【讨论】:

    • position_dodge() 不适用于日期的根本问题是什么?
    • @SamFirke 这是因为日期,因为比例是专门为日期定义的,所以标签中有重叠。向日期添加格式改变了一切!我希望这对你来说很清楚!
    猜你喜欢
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2023-01-31
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多