如何在 R 中对长表进行子集化并使用 ggplot 创建箱线图

How to subset a longtable in R and create boxplots with ggplot

给定以下示例:

set.seed(1)
tmp.data<-data.frame(group=rep(c("x","y","z"),8),
year=rep(c(2000:2003),6),
value=runif(24, 1, 100)) 

我可以创建一个简单的箱线图与团体关系:

boxplot.example<-ggplot(data=tmp.data)
boxplot.example.simple<-boxplot.example +
geom_boxplot(aes(x=group,y=value))

# plot
boxplot.example.simple

但是我想在同一图形中为每个组和年份创建单独的箱线图。

我用 ggplot 的组函数试过了:

boxplot.example.yearly<-boxplot.example +
geom_boxplot(aes(x=year,y=value, group=group))

# plot
boxplot.example.yearly # does not work as expected

但是分组没有按预期工作。

然后我尝试像这样使用 splitllply

require("plyr")

boxplot.example.yearly.2<-ggplot() +
llply(.data=split(tmp.data,tmp.data$year),.fun=geom_boxplot,
aes(x=year,y=value))

# Error: ggplot2 doesn't know how to deal with data of class uneval

这可能是因为在 ggplot 函数中没有指定数据参数。

那么我怎样才能将箱线图绘制成一个按 group 和年度观察分组的图表?

由于您想在同一图表中为每个组和年份生成箱线图,我认为您的数据集已准备就绪,您可以执行以下操作:

p <- ggplot(tmp.data, aes(factor(year), fill=group, value)) 
p + geom_boxplot()