考虑如下数据集
Col1 Col2
A BOY
B GIRL
A BOY
B BOY
A BOY
B GIRL
这两列都是分类变量。我想为两个变量制作一个分组的条形图,使用position =“ fill”将Y轴显示为比例
我怎么做 ?
这就是我所拥有的
ggplot(aboveData, aes(x =col1, fill = col2)) + geom_bar(position = "fill")
这显示为堆积的条形图。我想分组。
我们首先统计一下:
library(dplyr)
library(ggplot2)
df = structure(list(Col1 = structure(c(1L, 2L, 1L, 2L, 1L, 2L), .Label = c("A",
"B"), class = "factor"), Col2 = structure(c(1L, 2L, 1L, 1L, 1L,
2L), .Label = c("BOY", "GIRL"), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))
tab <- df %>% group_by(Col1,Col2,.drop=FALSE) %>% tally()
您不清楚按比例表示的意思。如果它在X变量中的比例(通常绘制),则:
tab %>% mutate(perc=n/sum(n)) %>%
ggplot() + geom_col(aes(x=Col1,y=perc,fill=Col2),position="dodge") +
scale_y_continuous(labels =scales::percent)
如果您指的是一切的一部分,那么:
tab %>% ungroup() %>%
mutate(perc=n/sum(n)) %>%
ggplot() + geom_col(aes(x=Col1,y=perc,fill=Col2),position="dodge") +
scale_y_continuous(labels =scales::percent)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句