side-by-side barplot with ggplot

前端 未结 1 1837
一向
一向 2020-12-21 07:55

I\'m trying to display a side-by-side bar plot that compares the counts of each a letter grade between the 2 columns. (A\'s next to each other, B\'s next to each other etc.)

相关标签:
1条回答
  • 2020-12-21 08:17

    You need to transform the data frame in a tidy form. For that you could use the tidyr package function gather. To ensure the correct sorting for the letter grade using an ordered factor is appropriate:

    library(tidyr)
    library(ggplot2)
    
    dat <- data.frame(grade1 = c('A','A','A','B','B','C'), grade2 = c('A','B','C','C','D','D'))
    
    tidy_dat <- gather(dat)
    tidy_dat[,2] <- ordered(tidy_dat[,2], levels = c('A','B','C','D'))
    
    ggplot(tidy_dat, aes(x= value, fill = key))+
       geom_bar(position = 'dodge')
    

    0 讨论(0)
提交回复
热议问题