Multiple boxplots on one plot with ggplot2

倾然丶 夕夏残阳落幕 提交于 2019-12-06 05:50:08

问题


Standard R plotting produces 30 boxplots in one plot when I use this code:

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

I would like to produce something similar in 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. In each year there are 145 species. In each year the 145 species are categorized into quartiles of 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? Any help much appreciated.

There are 30 years of data. In each year there are 145 species. In each year the 145 species are categorized into quartiles of 1-4.


回答1:


What does str(d1) tell you about x? If numeric or integer, then that could be your problem. If Year is a factor, then you get a boxplot for each 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

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

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


来源:https://stackoverflow.com/questions/10847506/multiple-boxplots-on-one-plot-with-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!