使用ggplot2在一个图上绘制多个箱线图

4

当我使用以下代码时,标准的R绘图会在一个图中生成30个箱线图:

boxplot(Abundance[Quartile==1]~Year[Quartile==1],col="LightBlue",main="Quartile1 (Rare)")

我想在ggplot2中制作类似的东西。到目前为止,我正在使用以下内容:

d1 = data.frame(x=data$Year[Quartile==1],y=data$Abundance[Quartile==1])
a <- ggplot(d1,aes(x,y))
a + geom_boxplot()

有30年的数据。每年有145个物种。每年,这145个物种被分为1-4的四分位数。但是,只能获得一个箱形图。请问如何在x轴上获取30个箱形图(每年一个)?非常感谢您的帮助。

2
Abundance数据是您自己的私有集吗?如果是,请创建一个可重现的示例,例如使用irismtcars - Andrie
1
凭直觉猜测,我认为您需要查看reshape2包的melt函数。 - Paolo
在组合多个ggplot时,还有一个值得关注的是gridExtra包及其grid.arrange函数。 - Etienne Low-Décarie
1个回答

9

str(d1)告诉您关于x的信息。如果是数字或整数,则可能是问题所在。如果Year是一个因子,则会为每个年份绘制一个箱线图。举个例子:

library(ggplot2)

# Some toy data
df <- data.frame(Year = rep(c(1:30), each=20), Value = rnorm(600))
str(df)

请注意,Year 是一个整型变量。
ggplot(df, aes(Year, Value)) + geom_boxplot()   # One boxplot

ggplot(df, aes(factor(Year), Value)) + geom_boxplot()   # 30 boxplots

太好了!我缺少的只是简单的“因子”!感谢您的帮助。 - JPD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接