【问题标题】:side-by-side barplot with ggplot与 ggplot 并排的条形图
【发布时间】:2017-06-24 09:32:40
【问题描述】:

我正在尝试显示一个并排的条形图,比较两列之间每个字母等级的计数。 (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 轴上有 4 个标签(A、B、C、D)。我应该使用特定的 dplyr 函数吗?

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

【问题讨论】:

标签: r ggplot2 dplyr


【解决方案1】:

您需要以整齐的形式转换数据框。为此,您可以使用 tidyr 封装函数gather。为了确保使用有序因子对字母等级进行正确排序是适当的:

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

【讨论】:

  • 刚刚想通了,但这更好。谢谢好心的先生!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2017-08-06
  • 2011-08-23
  • 1970-01-01
相关资源
最近更新 更多