我有类似 this one 的问题关于使用多个数据框绘制 ggplot。我想创建一个基本图,然后使用数据框列表添加数据(如下所述的基本原理/用例)。
library(ggplot2)
# generate some data and put it in a list
df1 <- data.frame(p=c(10,8,7,3,2,6,7,8),v=c(100,300,150,400,450,250,150,400))
df2 <- data.frame(p=c(10,8,6,4), v=c(150,250,350,400))
df3 <- data.frame(p=c(9,7,5,3), v=c(170,200,340,490))
l <- list(df1,df2,df3)
#create a layer-adding function
addlayer <-function(df,plt=p){
plt <- plt + geom_point(data=df, aes(x=p,y=v))
plt
}
#for loop works
p <- ggplot()
for(i in l){
p <- addlayer(i)
}
#Reduce throws and error
p <- ggplot()
gg <- Reduce(addlayer,l)
Error in as.vector(x, mode) :
cannot coerce type 'environment' to vector of type 'any'
Called from: as.vector(e2)
在编写这个示例时,我意识到 for 循环
是一个不错的选择,但我不介意 Reduce
的简洁性,尤其是当我想链接多个一起发挥作用。
对于那些感兴趣的人,我的用例是在 map 上的点之间绘制许多不连接的线。从引用数据框中,我认为最简洁的映射方法是生成一个子集数据框列表,每个数据框对应一行。我不希望它们连接,所以 geom_path
不好。
最佳答案
这似乎可行,
addlayer <-function(a, b){
a + geom_point(data=b, aes(x=p,y=v))
}
Reduce(addlayer, l, init=ggplot())
请注意,您还可以使用图层列表,
ggplot() + lapply(l, geom_point, mapping = aes(x=p,y=v))
然而,这两种策略都不推荐; ggplot2 完全有能力在单个层 中绘制多条未连接的线(使用例如 group 参数)。它是更高效、更简洁的代码。
names(l) = 1:3
m = ldply(l, I)
ggplot(m, aes(p, v, group=.id)) + geom_line()
关于r - 使用 Reduce 向 ggplot 添加图层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049265/