简体   繁体   English

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

[英]Multiple boxplots on one plot with ggplot2

Standard R plotting produces 30 boxplots in one plot when I use this code: 当我使用此代码时,标准R绘图在一个图中产生30个箱图:

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

I would like to produce something similar in ggplot2. 我想在ggplot2中生成类似的东西。 So far i'm using this: 到目前为止我正在使用这个:

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

There are 30 years of data. 有30年的数据。 In each year there are 145 species. 每年有145种。 In each year the 145 species are categorized into quartiles of 1-4. 在每年,145种物种被分为1-4的四分位数。

However, I'm only getting a single boxplot using this. 但是,我只使用它来获得一个盒子图。 Any idea how to get 30 boxplots (one for each year) along the x axes? 知道如何沿x轴获得30个箱图(每年一个)吗? Any help much appreciated. 任何帮助非常感谢。

There are 30 years of data. 有30年的数据。 In each year there are 145 species. 每年有145种。 In each year the 145 species are categorized into quartiles of 1-4. 在每年,145种物种被分为1-4的四分位数。

What does str(d1) tell you about x ? str(d1)告诉你什么x If numeric or integer, then that could be your problem. 如果是数字或整数,那么这可能是你的问题。 If Year is a factor, then you get a boxplot for each Year. 如果Year是一个因素,那么每个年份都会得到一个箱线图。 As an example: 举个例子:

library(ggplot2)

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

Note that Year is an integer variable 请注意, Year是一个整数变量

ggplot(df, aes(Year, Value)) + geom_boxplot()   # One boxplot

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM