R语言 填充一组多面图中的缺失值

9cbw7uwe  于 2023-03-20  发布在  其他
关注(0)|答案(2)|浏览(146)
df <- data.frame(percent=c(3, 5, 2),
                 method=c("A", "A", "B"),
                 ancestry=c("European", "African", 'African'),
                 pair=c('pair one', 'pair two','pair two'))
p1 <- ggplot(data=df, aes(x=pair, y=percent, fill=ancestry)) +
geom_bar(stat="identity", position=position_dodge()) + facet_wrap(~ method)
p1 <- p1 + geom_text(aes(label=percent), position=position_dodge(width=0.9))

给了我这个:

但我希望这样

有简单的方法吗?

blpfk2vs

blpfk2vs1#

要避免手动填充缺少的变量组合,可以使用tidyr::complete

library(tidyverse)

df %>%
  complete(expand(df, method, pair), fill = list(percent = 0)) %>%
  ggplot(aes(pair, percent, fill = ancestry)) +
  geom_col() + 
  geom_text(aes(label = percent), size = 6, vjust = -0.2,
            position = position_dodge(width = 0.9)) +
  facet_wrap(~ method) +
  scale_fill_brewer(palette = "Set2", breaks = unique(df$ancestry)) +
  theme_bw(base_size = 16)

bvuwiixz

bvuwiixz2#

您可以添加“零”行,并将ancestry更改为因子:

df = bind_rows(df, data.frame(percent=0, method="B", ancestry="European", pair="pair one")) %>% 
  mutate(ancestry=factor(ancestry, levels = c("European", "African")))

现在,p1的输出如下:

相关问题