根据显示百分比的第三个变量,带有两个分类变量 facet_wrap 的 ggplot2 的条形图

Barplot with ggplot 2 of two categorical variable facet_wrap according a third variable displayng percentage

我想在 ggplot2 中绘制一个根据第二个分类变量分组的分类变量,并使用 facet_wrap 将它们划分到不同的图中。 比我会显示每个的百分比。这是一个可重现的例子

test <- data.frame(
  test1 = sample(letters[1:2], 100, replace = TRUE), 
  test2 = sample(letters[3:5], 100, replace = TRUE),
  test3 = sample(letters[9:11],100, replace = TRUE )
)


ggplot(test, aes(x=factor(test1))) +
  geom_bar(aes(fill=factor(test2), y=..prop.., group=factor(test2)), position="dodge") +
  facet_wrap(~factor(test3))+
  scale_y_continuous("Percentage (%)", limits = c(0, 1), breaks = seq(0, 1, by=0.1), labels = percent)+
  scale_x_discrete("")+
  theme(plot.title = element_text(hjust = 0.5), panel.grid.major.x = element_blank())

这给了我一个条形图,其中包含每个测试 3 中测试 1 的测试 2 的百分比。 我想在顶部显示每个栏的百分比。另外,我想把Test2中factor(test2)右边的图例改成名字

您自己进行数据汇总可能是最简单的方法,这样您就可以创建一个包含所需百分比标签的列。 (请注意,我不确定您希望百分比显示什么 - 在方面 i,组 b 中,有一列接近 90%,两列大于或等于 50%- 是那是故意的?)

库和您的示例数据框:

library(ggplot2)
library(dplyr)

test <- data.frame(
  test1 = sample(letters[1:2], 100, replace = TRUE), 
  test2 = sample(letters[3:5], 100, replace = TRUE),
  test3 = sample(letters[9:11],100, replace = TRUE )
)

首先对所有列进行分组(注意顺序),然​​后汇总得到test2lengthMutate 获取列高和标签的值- 这里我乘以 100 并四舍五入。

test.grouped <- test %>%
  group_by(test1, test3, test2) %>%
  summarize(t2.len = length(test2)) %>%
  mutate(t2.prop = round(t2.len / sum(t2.len) * 100, 1))

> test.grouped
# A tibble: 18 x 5
# Groups:   test1, test3 [6]
    test1  test3  test2 t2.len t2.prop
   <fctr> <fctr> <fctr>  <int>   <dbl>
 1      a      i      c      4    30.8
 2      a      i      d      5    38.5
 3      a      i      e      4    30.8
 4      a      j      c      3    20.0
 5      a      j      d      8    53.3
...

使用汇总数据构建您的绘图,使用geom_text使用比例列作为标签:

ggplot(test.grouped, aes(x = test1, 
                         y = t2.prop, 
                         fill = test2, 
                         group = test2)) +  
  geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
  geom_text(aes(label = paste(t2.prop, "%", sep = ""), 
                group = test2), 
            position = position_dodge(width = 0.9),
            vjust = -0.8)+
  facet_wrap(~ test3) + 
  scale_y_continuous("Percentage (%)") +
  scale_x_discrete("") + 
  theme(plot.title = element_text(hjust = 0.5), panel.grid.major.x = element_blank())