ggplot2 中各组百分比的条形图

Barplot of percentages by groups in ggplot2

所以,我已经完成了搜索,但找不到解决这个问题的方法,我在 ggplot 中使用条形图。 我正在尝试使条形图占分组变量 2 中每组案例总数的百分比。

现在我可以将计数可视化,

Dataframe = 尽快

分组变量 1 - cc_groups(见图表顶部) (计算 0-100 分数范围内(步长为 20)的案例数。)

分组变量 2 - asap (有干预或控制的二元变量,控制和干预的数量不同)

初始代码

``` r
ggplot(ASAP, aes(x = asap, fill = asap)) + geom_bar(position = "dodge") + 
    facet_grid(. ~ cc_groups) + scale_fill_manual(values = c("red", 
    "darkgray"))
#> Error in ggplot(ASAP, aes(x = asap, fill = asap)): could not find function "ggplot"
```

reprex package (v0.3.0)

于 2020-05-19 创建

这给了我下图,它是每个子组中计数的可视化。

enter image description here

我手动计算了实际需要可视化的不同百分比:

table_groups <- matrix(c(66/120,128/258,34/120,67/258,10/120,30/258,2/120,4/258,0,1/258,8/120,28/258),ncol = 2, byrow = T)
colnames(table_groups) <- c("ASAP","Control")
rownames(table_groups) <- c("0-10","20-39","40-59","60-79","80-99","100")


         ASAP  Control
0-10  0.55000 0.496124
20-39 0.28333 0.259690
40-59 0.08333 0.116279
60-79 0.01667 0.015504
80-99 0.00000 0.003876
100   0.06667 0.108527

当我使用下面 Stefan 提供的解决方案时(这是一个很好的答案,但没有真正发挥作用。我得到以下输出

    ``` r
ASAP %>% count(cc_groups, asap) %>% group_by(cc_groups) %>% mutate(pct = n/sum(n)) %>% 
    ggplot(aes(x = asap, y = pct, fill = asap)) + geom_col(position = "dodge") + 
    facet_grid(~cc_groups) + scale_fill_manual(values = c("red", 
    "darkgray"))
#> Error in ASAP %>% count(cc_groups, asap) %>% group_by(cc_groups) %>% mutate(pct = n/sum(n)) %>% : could not find function "%>%"
```

<sup>Created on 2020-05-19 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>

enter image description here

然而(当我使用模拟时)我喜欢它像上面这样显示百分比。

enter image description here

我对那幅画感到很抱歉.. :) 并且 reprex 一直给我错误,我确定我使用它不正确。

实现这一点的最简单方法是在绘图之前聚合数据,即手动计算计数和百分比:

library(ggplot2)
library(dplyr)

ASAP %>% 
  count(cc_groups, asap) %>% 
  group_by(asap) %>% 
  mutate(pct = n / sum(n)) %>%   
  ggplot(aes(x = asap, y = pct, fill=asap)) + 
  geom_col(position="dodge")+
  facet_grid(~cc_groups)+
  scale_fill_manual(values = c("red","darkgray"))

使用 ggplot2::mpg 作为示例数据:

library(ggplot2)
library(dplyr)

# example data
mpg2 <- mpg %>% 
  filter(cyl %in% c(4, 6)) %>% 
  mutate(cyl = factor(cyl))

# Manually compute counts and percentages
mpg3 <- mpg2 %>% 
  count(class, cyl) %>% 
  group_by(class) %>% 
  mutate(pct = n / sum(n)) 

# Plot 
ggplot(mpg3, aes(x = cyl, y = pct, fill = cyl)) +
  geom_col(position = "dodge") +
  facet_grid(~ class) +
  scale_fill_manual(values = c("red","darkgray"))

reprex package (v0.3.0)

于 2020-05-18 创建