R语言 标签在堆叠条形图中重叠时的位置

jv2fixgn  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(198)

我一直在处理几个堆叠条形图,但有些柱形图太小,无法容纳标签,导致标签重叠,无法读取。请参见下图:

请考虑生成上图的以下MWE。

问:是否可以从标签中添加指向条形图位置的线条?这样它们就可以偏移,更容易阅读?

tribble(
~parm, ~value,
"b1", 0.009,
"g1", 0.664,
"b2", 0.000,
"ra", 0.000,
"rc", 0.000,
"ax", 0.084,
"cx", 0.086,
"ex", 0.179,
"ay", 0.045,
"cy", 0.043,
"ey", 0.102
) -> doc1

 
 
doc2 <- tribble(
  ~parm, ~value,
  "b1", 0.181,
  "g1", 0.289,
  "b2", 0.181,
  "ra", 0.000,
  "rc", 0.000,
  "ax", 0.001,
  "cx", 0.001,
  "ex", 0.002,
  "ay", 0.001,
  "cy", 0.001,
  "ey", 0.002,
  "re", 0.000,
  "rf", 0.000,
  "b3", 0.289
)

doc1 <- doc1 %>% mutate(model = "exp")
doc2 <- doc2 %>% mutate(model = "exp2")

finalpow <- doc1 %>% full_join(doc2)

# Make a stacked bar plot
ggplot(finalpow, aes(x = model, y = value, fill = parm)) +
  geom_bar(stat = "identity", color = "black") +
    geom_text(aes(label = parm), position = position_stack(vjust = 0.5)) +
  theme_luis() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(x = "Parameter", y = "Variance explained in NCP", fill = "Parameter") +
  scale_y_continuous() +
  coord_flip()
eufgjt7s

eufgjt7s1#

正如@Camille在评论中建议的那样,可以将ggrepelgeom_text_repel函数结合使用,然后将其替换为geom_text。如果愿意,可以使用max.overlaps。下面是一些可复制的代码:

library(dplyr)
library(ggplot2)
library(ggrepel)
doc1 <- doc1 %>% mutate(model = "exp")
doc2 <- doc2 %>% mutate(model = "exp2")

finalpow <- doc1 %>% full_join(doc2)
#> Joining, by = c("parm", "value", "model")

# Make a stacked bar plot
ggplot(finalpow, aes(x = model, y = value, fill = parm)) +
  geom_bar(stat = "identity", color = "black") +
  geom_text_repel(aes(label = parm), position = position_stack(vjust = 0.5)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(x = "Parameter", y = "Variance explained in NCP", fill = "Parameter") +
  scale_y_continuous() +
  coord_flip()

创建于2022年12月24日,使用reprex v2.0.2
请查看上面的链接,了解更多关于这个软件包的好例子。

相关问题