ggplot2标签不会与geom_col条一起闪避

问题描述

我经历了相关的问题,这些答案并不能解决我的标签无法躲避geom_col条的问题:

数据

x <- structure(
  list(capacity = c(0,2.1,3.1,4,4.6,5.6,6,1.9,2.3,3.8),year = c("FY21","FY21","FY20","FY19","FY19"),unified_date = structure(c(18536,18567,18597,18628,18659,18536,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)

图表

not-dodged ggplot

我尝试将fill = year添加geom_text aesgroup = year上,在aes的变体附近移动position_dodge()的值-什么都没有。

解决方法

尝试一下:

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

输出:

enter image description here

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

#Code 2
x %>% mutate(Month=format(unified_date,'%b')) %>%
  mutate(Month=factor(Month,levels = unique(Month),ordered = T)) %>%
  ggplot2::ggplot(aes(x = Month,vjust=-0.5)+
  xlab('Date')

输出:

enter image description here