gpt4 book ai didi

r - 在ggplot2中循环数据帧

转载 作者:行者123 更新时间:2023-12-03 02:24:53 25 4
gpt4 key购买 nike

我想使用来自多个不同数据帧的 ggplot 绘制一系列绘图。我计划使用一个列表并按如下方式迭代该列表:

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 数据的子集,但这似乎增加了更多工作。

最佳答案

迭代 data.frames(只是定期组织的列表)的常用方法是使用 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-objects 列表的情况下,我想 Hadley 方法将使用 llply,但我不是熟练的 plyr 用户,所以让我建议这个完全未经测试的代码模板:

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)

关于r - 在ggplot2中循环数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7787902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com