首页 文章

R - ggplot2 - 用两个因子绘制一个因子

提问于
浏览
1

我正在关注此链接:ggplot2 bar plot with two categorical variables

我的问题非常相似 - 我需要做OP需要的但我需要用另一个因素来分割计数条 .

让我说明一下:

>     var response_cat has values 0,1 (categories of a response) 
>     
>     var group indicates belonging to a group (0,1) 
>     
>     var item indicates the name of an item (20 strings with codes like LY1, GN6,...)

我需要绘制如下图形:x轴每个项目有两个条形(对于每个组),y轴的相对频率为1

有任何想法吗?

谢谢!

1 回答

  • 1

    我们可以用 facet_wrap

    library(tidyverse)
    df %>%
       group_by_at(names(.)) %>%
       summarise(n = n()) %>%
       ggplot(., aes(x = Fruit, y = n, fill = Bug)) + 
       geom_bar(stat = "identity") +
       facet_wrap(~ group)
    

    enter image description here

    数据

    Fruit <- c(rep("Apple",3),rep("Orange",5))
    Bug <- c("worm","spider","spider","worm","worm","worm","worm","spider")
    group <- rep(LETTERS[1:2], each = 4)
    df <- data.frame(Fruit,Bug, group)
    

相关问题