Search code examples
rdataframebar-chartlines

Plot by lines of a data frame in R


I have a table looking like this

         hashtag  Daily_Freq men women 
          #a          10       6     4  
          #b          15       5    10   
          #c          20       8    12  

I want to plot for each data frame line, i.e. for each hashtag, the frequency of men and women. In this case I would want to plot 3 barplots, each one with two columns - one for men and anoher for women frequencies. How can I do this?


Solution

  • One solution is using gather and ggplot2 as:

    #data
    df <- read.table(text = "hashtag  Daily_Freq men women 
    '#a'          10       6     4  
    '#b'          15       5    10   
    '#c'          20       8    12", header = T, stringsAsFactors = F)
    
    library(tidyverse)
    df <- df %>% select(-Daily_Freq) %>%
             gather(key = Gender, value, -hashtag)
    
    library(ggplot2)
    ggplot(df, aes(x=hashtag, y=value, fill=Gender)) +
    geom_bar(stat='identity', position='dodge')
    

    enter image description here

    Option #2

    ggplot(df, aes(x=Gender, y=value)) +
      geom_bar(stat='identity', position='dodge') + facet_grid(~ hashtag)
    

    enter image description here