I have question similar to this one about the use of multiple dataframes for plotting a ggplot. I would like to create a base plot and then add data using a list of dataframes (rationale/usecase described below).
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)
In writing out this example I realize that the for loop
is not a bad option but wouldn't mind the conciseness of Reduce
, especially if I want to chain several functions together.
For those who are interested my use case is to draw a number of unconnected lines between points on a map. From a reference dataframe I figured the most concise way to map was to generate a list of subsetted dataframes, each of which corresponds to a single line. I don't want them connected so geom_path
is no good.