控制 geom_text 标签在具有正值和负值以及具有不同比例的面的条形图中的位置

Controlling the position of geom_text labels in a bar plot with positive and negative values and facets with different scales

我希望标签出现在正条和负条的外面,所以我不能简单地使用 hjust 来移动位置。现在我有这个,很接近...

score <- c(1, 2, 3, 4, 5, "X")
group1 <- c(0,0,5,-0.2,-4.9,0)
group2 <- c(0.1,0,-1.2,0.4,0.6,0.1)
group3 <- c(0.1,0,3.4,2.9,-6.4,0)
group4 <-c(0,0,-0.9,-0.3,1.3,0)

data <- data.frame(score=as.factor(score), Group1=group1, Group2=group2, Group3=group3, Group4=group4)

data_long <- pivot_longer(data, c(Group1, Group2, Group3, Group4))
data_long$label <- paste(round(data_long$value,1),"%",sep="")
data_long$value <- data_long$value/100

sig <- rep(0, 24)
sig[c(3, 9, 11, 15, 17, 19)] <- 1
sig <- as.factor(sig)
data_long <- cbind(data_long, sig)


bars <- data_long %>% filter(score != 2,
                             score != "X") %>%
  ggplot(aes(x = value, y=name, fill=sig))+ 
  geom_bar(stat="identity") +
  scale_fill_manual(values=c("grey", "firebrick")) +
  scale_x_continuous(limits = ~ c(-1, 1) * max(abs(.x)),
                     labels = scales::percent) +
  facet_wrap(~score, scales = "free_x") +
  theme(legend.position = "none") +
  geom_text(aes(label=label,
                x = value + (0.005 * sign(value))),  size = 3) +
  labs(x = "Deviation From Expected Value",
       y = "Group",
       title = "Deviations From Expected Value by Score",
       caption = "Red bars statistically significant")

print(bars)

这将生成以下图表

但请注意在左上角,比例非常小,标签与非零条的距离非常远。我假设这是因为我在 geom_text x 美学中使用的乘法因子对于该比例来说很大。我在那里尝试了某种考虑了限制的功能,但我得到了一个错误

Aesthetics must be valid data columns. Problematic aesthetic(s): x = ~(value + (0.005 * max(abs(.x)) * sign(value)))

任何关于如何进行的建议都将不胜感激。

您可以使用hjust作为美学映射。如果将其设置为 0.5 - sign(value)/2,则根据需要,正条为 0,负条为 1。

data_long %>% filter(score != 2,
                             score != "X") %>%
  ggplot(aes(x = value, y=name, fill=sig))+ 
  geom_bar(stat="identity") +
  scale_fill_manual(values=c("grey", "firebrick")) +
  scale_x_continuous(limits = ~ c(-1, 1) * max(abs(.x)),
                     labels = scales::percent) +
  facet_wrap(~score, scales = "free_x") +
  theme(legend.position = "none") +
  geom_text(aes(label=label,
                x = value, hjust = 0.5 - sign(value)/2),  size = 3) +
  labs(x = "Deviation From Expected Value",
       y = "Group",
       title = "Deviations From Expected Value by Score",
       caption = "Red bars statistically significant")