繁体   English   中英

控制position条中geom_text标签plot正负值和刻面不同尺度

[英]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 美学中使用的乘法因子对于该比例来说很大。 我在那里尝试了某种 function,它考虑了限制,但我得到了一个错误

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")

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM