我有这个数据,我想得到 y 轴的百分比。
structure(list(sb_1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("0", "x"), class = "factor"),
sb_2 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "0", class = "factor"), sb_3 = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "b", class = "factor"),
sb_4 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L), .Label = c("0", "c"), class = "factor"), wave = structure(c(1L,
2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("h",
"j"), class = "factor")), row.names = c(NA, 12L), class = "data.frame")
这是我使用的代码:
nn%>%
pivot_longer(cols = starts_with("sb_")) %>%
filter(value != 0) %>%
unite(sb_, name, value) %>%
group_by(wave) %>%
mutate(wave_total = n()) %>%
group_by(sb_, .add = TRUE) %>%
mutate(sb_pct = 100 * n() / wave_total) %>%
ggplot(aes(x = factor(sb_, levels = str_sort(unique(sb_), numeric = TRUE)), y = sb_pct)) +
geom_bar(aes(fill = wave), stat = "identity", position = position_dodge(preserve = "single")) +
xlab("sb") +
ylab("percent")
结果是:![1]
结果应该不同,因为例如对于第一列,没有零,都是结果。
sb_1 sb_2 sb_3 sb_4 wave
1 0 0 b 0 h
2 0 0 b 0 j
3 0 0 b 0 h
4 0 0 b c j
5 0 0 b c h
6 0 0 b c j
7 x 0 b c h
8 x 0 b c j
9 x 0 b c h
10 x 0 b c j
11 x 0 b c h
12 x 0 b c j
所以请帮助我为什么不正确?