ggplot条形图中每个条的计数百分比

时间:2019-04-15 16:21:10

标签: r ggplot2

我有一个填充有两个级别的条形图,y轴归类为0,1。条形图现在显示0计数和1计数,我想显示每个条形图上每个条形图的各个百分比,以便我可以看到哪个条形图最高,然后再查看每个条形图哪个更高。但是我的数量是绝对的

我想将每个条形图的百分比显示为100%,然后分成几组。

ggplot(stackoverflow,aes(x = stackoverflow $ person,fill = stackoverflow $ success))+ facet_wrap(〜stackoverflow $ city)+ geom_bar()

Like this

   structure(list(data = structure(list(source = structure(c(1L, 
1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("p", 
"q", "r"), class = "factor"), person = structure(c(1L, 1L, 1L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 1L), .Label = c("a", "b", 
"c"), class = "factor"), city = structure(c(1L, 1L, 3L, 3L, 3L, 
2L, 1L, 1L, 1L, 3L, 3L, 3L, 3L), .Label = c("x", "y", "z"), class = "factor"), 
    success = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 
    1L, 2L, 2L, 2L), .Label = c("0", "1"), class = "factor")), row.names = c(NA, 
-13L), class = "data.frame"), layers = list(<environment>), scales = <environment>, 
    mapping = structure(list(x = ~stackoverflow$person, fill = ~stackoverflow$success), class = "uneval"), 
    theme = list(), coordinates = <environment>, facet = <environment>, 
    plot_env = <environment>, labels = list(x = "stackoverflow$person", 
        fill = "stackoverflow$success", y = "count", weight = "weight")), class = c("gg", 
"ggplot"))

1 个答案:

答案 0 :(得分:1)

首先使用tidyverse进行数据聚合:

dk %>% 
group_by(person, city, success) %>% 
summarise(counts = n()) %>% 
right_join(dk %>% 
           group_by(city, person) %>% 
           summarise(all_counts= n())) %>% 
mutate(percents = paste0(round(counts/all_counts * 100, 2), "%")) %>% 
ggplot(aes(x = person, y = counts, fill = as.factor(success))) + 
geom_bar(stat = "identity") + 
geom_text(aes(label = percents), position = position_stack(vjust = 0.5)) +
facet_wrap(~city) + 
coord_flip()

实际上,我首先找到给定successperson的{​​{1}}的计数,然后将其除以总数(city),即总数给定all_counts的{​​{1}}中。然后我们找到people,然后使用city对其进行绘制。因为这些是汇总的,所以我们将percents与(ggplot)一起使用,并使用geom_bar,它会打印百分比(stat = "identity"将标签居中)。最后,我们基于geom_text position_stack(vjust = 0.5)facet行会翻转x和y轴。