与ggplot并排的barplot [英] side-by-side barplot with ggplot

查看:201
本文介绍了与ggplot并排的barplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示一个并排的条形图,比较两列之间每个字母等级的计数。 (A彼此相邻,B彼此相邻等)

 > dat = data.frame(grade1 = c('A','A','A','B','B','C'),grade2 = c('A','B','C' ,'C','D','D'))
> dat
grade1 grade2
1 A a
2 A b
3 A C
4 B C
5 B D
6 C D
> ggplot(dat,aes(x = grade1,fill = grade2))+
geom_bar(position = position_dodge())

我试图得到一个类似于x轴(A,B,C,D)上的4个标签的结果。是否有一个特定的dplyr函数,我应该使用?




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

> dat = data.frame(grade1 = c('A','A','A','B','B','C'), grade2 = c('A','B','C','C','D','D'))
> dat
  grade1 grade2
1      A      A
2      A      B
3      A      C
4      B      C
5      B      D
6      C      D
> ggplot(dat, aes(x=grade1, fill=grade2)) +
   geom_bar(position=position_dodge())

I'm trying to get a result that looks something like this with 4 labels on the x-axis (A, B, C, D). Is there a particular dplyr function I should be using?

https://i0.wp.com/martinsbioblogg.files.wordpress.com/2014/03/means-barplot.png

解决方案

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')

这篇关于与ggplot并排的barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆