循环在ggplot2中的数据帧 [英] loop over dataframes in ggplot2
问题描述
我想使用ggplot从多个不同的数据框中进行一系列绘图.我打算使用一个列表,并按如下所示遍历该列表:
I would like to make a series of plots using ggplot from multiple different dataframes. I was planning on using a list and iterating over the list as follows:
libraries <- objects() #make a list of the dataframes we want to graph
for(i in libraries) {
# create initial plots
x1 <- qplot(data= i, V1, reorder(V2,V3), color = V3) + coord_flip()
x2 <- ggplot(i, aes(x=reorder(V2,V3), group=V3, color=V3)) + geom_bar()
x3 <- ggplot(i, aes(x=V1, group=V3, color=V3)) + coord_flip() + geom_bar()
}
但是我收到错误消息:
Error: ggplot2 doesn't know how to deal with data of class factor
大概是因为库"现在是一个字符变量,而不是一个数据帧.有人对如何遍历数据框有其他建议吗?我想我可以将它们与plyr合并,然后ggplot数据的子集,但这似乎增加了更多的工作.
presumably because 'libraries' is now a character variable and not a data frame. Any one have another suggestion on how to iterate through the dataframes? I suppose I could merge them with plyr and then ggplot a subset of the data but that seems to add more work.
推荐答案
迭代data.frames(通常是定期组织的列表)的通常方法是使用 lapply
:
The usual way to iterate over data.frames (which are just regularly organized lists) is with lapply
:
df1 <- data.frame(date = as.Date(10*365*rbeta(100, .5, .1)),group="a")
df2 <- data.frame(date = as.Date(10*365*rbeta(50, .1, .5)),group="b")
df3 <- data.frame(date = as.Date(10*365*rbeta(25, 3,3)),group="c")
dfrmL <- list(df1,df2,df3)
lapply(dfrmL, NROW)
[[1]]
[1] 100
[[2]]
[1] 50
[[3]]
[1] 25
在生成ggplot对象列表的情况下,我想像一下Hadley方法将改为使用 llply
,但是我不是熟练的plyr用户,所以让我建议这个完全未经测试的代码模板:
In the case of producing a list of ggplot-objects I would imagine that the Hadley-method would instead be to use llply
, but I'm not a skilled plyr-user, so let me suggest this totally untested code template:
plts <- lapply(dfrmL, function(df) qplot(qplot(data= df,
V1, reorder(V2,V3), color = V3) +
coord_flip()
)
# you may need to explicitly print() or plot() the plots as stated in the R-FAQ.
lapply(plts, print)
这篇关于循环在ggplot2中的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!