对于R中的以下data.frame,我如何制作按Treatment Type
分组的条形图?每个条形的高度代表Number of Occurrences
。 Species A
和Species 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
答案 0 :(得分:4)
假设“group”,你的意思是二进制变量Type
,我有以下两种解决方案,分别使用lattice
和ggplot2
包:
在绘图之前,我重构了一个(限量版?)你的数据:
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))
)
第二种方法,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")