在分组闪避条形图中对齐 geom_text

Aligning geom_text in grouped dodged barplot

我的 df 是这样的:

Sede
<chr>
Mes
<S3: POSIXct>
n
<int>
Las Heras   2019-01-01  54      
Las Heras   2019-02-01  53      
Las Heras   2019-03-01  60      
Las Heras   2019-04-01  56      
Las Heras   2019-05-01  77      
Las Heras   2019-06-01  98      
Las Heras   2019-07-01  103     
Las Heras   2019-08-01  88      
Las Heras   2019-09-01  72      
Las Heras   2019-10-01  75      
Las Heras   2019-11-01  87      
Las Heras   2019-12-01  52      
Saavedra    2019-01-01  50      
Saavedra    2019-02-01  50      
Saavedra    2019-03-01  62      
Saavedra    2019-04-01  89

我的条形图代码:

ggplot(total_screening_mensual, aes(x = Mes, y = n, fill = Sede)) +
                geom_col(position = "dodge") +
                scale_fill_brewer(palette="Pastel1") +
              geom_text(aes(group = Sede, label = n), position = position_dodge2(width = 1), hjust = 0, vjust = .5, size = 3) +
                        coord_flip() +
                        labs(title = "Estudios de screening por sede durante 2019",
                    x = "Mes",
                    y = "Cantidad de estudios") 

我的剧情:

我希望文本与每一列对齐,但无法避开数字。我已经检查了很多类似的问题,但是 none 的答案似乎解决了这个问题,我不明白我在哪里弄错了...

问题是您试图在连续轴上躲避文本(您翻转的 x 轴是日期时间轴),而您可能希望它是一个离散轴。所以你可以这样做:

ggplot(total_screening_mensual, 
       aes(x = factor(Mes), y = n, fill = Sede)) +
  geom_col(position = position_dodge(width = 1)) +
  scale_fill_brewer(palette = "Pastel1") +
  geom_text(aes(label = n, group = Sede), 
            position = position_dodge(width = 1), 
            hjust = -0.2, vjust = 0.5, size = 3) +
  coord_flip() +
  scale_x_discrete(labels = function(x) strftime(x, "%b %Y")) +
  labs(title = "Estudios de screening por sede durante 2019",
       x = "Mes",
       y = "Cantidad de estudios") 


数据

total_screening_mensual <- 
  structure(list(Sede = c("Las Heras", "Las Heras", "Las Heras", 
  "Las Heras", "Las Heras", "Las Heras", "Las Heras", "Las Heras", 
  "Las Heras", "Las Heras", "Las Heras", "Las Heras", "Saavedra", 
  "Saavedra", "Saavedra", "Saavedra", "Saavedra", 
  "Saavedra", "Saavedra", "Saavedra", "Saavedra", 
  "Saavedra", "Saavedra", "Saavedra"), Mes = structure(c(1546300800, 
  1548979200, 1551398400, 1554073200, 1556665200, 1559343600, 1561935600, 
  1564614000, 1567292400, 1569884400, 1572566400, 1575158400, 1546300800, 
  1548979200, 1551398400, 1554073200, 1556665200, 1559343600, 1561935600, 
  1564614000, 1567292400, 1569884400, 1572566400, 1575158400), 
  class = c("POSIXct", "POSIXt"
  ), tzone = ""), n = c(54L, 53L, 60L, 56L, 77L, 98L, 103L, 88L, 
  72L, 75L, 87L, 52L, 50L, 50L, 62L, 89L, 74L, 86L, 103L, 94L,
  78L, 91L, 70L, 68L)), row.names = c(NA, -24L
  ), class = "data.frame")