Search code examples
rggplot2histogramfrequency

How to plot counts stackbar in ggplot2 R?


Dataset contains "two friends" and coded "interaction" (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.

Friend1 <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Friend2 <- c("1","1","2","2","1","1","2","2","1","1","2","2","1","1","2","2")
Interaction <- c("O","X","D","D","D","X","X","D/R","O","X","D","D","D","X","X","D/R")

df <- data.frame(Friend1, Friend2, Interaction)
df$Friend1 <- as.factor(as.character(df$Friend1))
df$Friend2 <- as.factor(as.character(df$Friend2))
df$Interaction <- as.factor(as.character(df$Interaction))

ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2)) + 
    geom_bar(position="fill", stat="identity", color = "white") + theme_classic() + theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black", size=1)) +   theme(strip.background = element_blank()) + facet_grid(.~Friend1)

Erorr: Error in UseMethod("count") : 
  no applicable method for 'count' applied to an object of class "character"

How do I "count" these factors to visualize frequency of interactions?


Solution

  • The issue is that dplyr::count expects a dataframe as its first argument and returns a dataframe. However, there is no reason to compute the counts as geom_bar will do that by default, i.e. get rid of y=... and stat="identity":

    library(ggplot2)
    
    ggplot(df, aes(fill = Interaction, x = Friend2)) +
      geom_bar(position = "fill", color = "white") +
      theme_classic() +
      theme(
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black", size = 1)
      ) +
      theme(strip.background = element_blank()) +
      facet_grid(. ~ Friend1)
    

    enter image description here