如何制作条形图,其中X来自数据框的多个值?
假数据:
data <- data.frame(col1 = rep(c("A", "B", "C", "B", "C", "A", "A", "B", "B", "A", "C")),
col2 = rep(c(2012, 2012, 2012, 2013, 2013, 2014, 2014, 2014, 2015, 2015, 2015)),
col3 = rep(c("Up", "Down", "Up", "Up", "Down", "Left", "Right", "Up", "Right", "Down", "Up")),
col4 = rep(c("Y", "N", "N", "N", "Y", "N", "Y", "Y", "Y", "N", "Y")))
Run Code Online (Sandbox Code Playgroud)
我正在试图做的是情节的数量(也,理想情况下,百分比)Y的和N在的col4基础上通过分组col1,col2和col3.
总的来说,如果有50行,其中有25行Y,我应该可以创建一个如下所示的图形:
我知道ggplot的基本条形图是:
ggplot(data, aes(x = col1, fil = col4)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)
我不是在寻找有多少col4每个被发现col3的col2,虽然如此,facet_wrap()不招,我想,但我不知道该怎么做.
您需要先将数据帧转换为长格式,然后使用创建的变量来设置facet_wrap().
data_long <- tidyr::gather(data, key = type_col, value = categories, -col4)
ggplot(data_long, aes(x = categories, fill = col4)) +
geom_bar() +
facet_wrap(~ type_col, scales = "free_x")
Run Code Online (Sandbox Code Playgroud)