R中的分组条形图

时间:2017-02-25 17:40:53

标签: r dataframe data-visualization

对于R中的以下data.frame,我如何制作按Treatment Type分组的条形图?每个条形的高度代表Number of OccurrencesSpecies ASpecies B将是彼此相邻绘制的两个独立条形图。

`Treatment Type`      Species    `Number of Occurrences`
         <chr>         <chr>                    <dbl>
Treatment           Species A                    10
Control             Species A                    15
Treatment           Species B                    55
Control             Species B                     5

1 个答案:

答案 0 :(得分:4)

假设“group”,你的意思是二进制变量Type,我有以下两种解决方案,分别使用latticeggplot2包:

在绘图之前,我重构了一个(限量版?)你的数据:

df <- data.frame(
  Type = rep(c("Treatment", "Control"), 2),
  Species = c(rep("Species A", 2), rep("Species B", 2)),
  Number_of_Occurrences = c(10, 15, 55, 5)
)
df
# Type   Species Number_of_Occurrences
# 1 Treatment Species A                    10
# 2   Control Species A                    15
# 3 Treatment Species B                    55
# 4   Control Species B                     5

第一种方法:lattice包:

library(lattice)
barchart(
  Number_of_Occurrences~Species,
  data=df, groups=Type, 
  scales=list(x=list(rot=90,cex=0.8))
)

enter image description here

第二种方法,ggplot2包;您需要使用reshape::melt函数重新格式化data.frame以满足ggplot2

的要求
library(reshape)
library(ggplot2)
df.m <- melt(df)
df.m
# Type   Species              variable value
# 1 Treatment Species A Number_of_Occurrences    10
# 2   Control Species A Number_of_Occurrences    15
# 3 Treatment Species B Number_of_Occurrences    55
# 4   Control Species B Number_of_Occurrences     5
ggplot(df.m, aes(Species, value, fill = Type)) + 
  geom_bar(stat="identity", position = "dodge")

enter image description here

参考:this Stack Overflow post