Petr Palíšek
Petr Palíšek

Reputation: 57

R - ggplot2 - plotting one factor by two factors

I'm following up on this link: ggplot2 bar plot with two categorical variables

My problem is very similar – I need to do what the OP needed but I need to split the count bars by another factor.

Let me illustrate:

>     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,...)

And I need to draw a graph as follows: x axis has two bars per item (for each group) y axis has relative frequencies of ones

any ideas?

thank you!

Upvotes: 1

Views: 891

Answers (1)

akrun
akrun

Reputation: 886938

We could use 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

data

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)

Upvotes: 3

Related Questions