Reputation: 303
Problem: I have three dataframes, "d1", "d2" and "d3" having three rows, X1, X2 and value. I want to plot several lines together using X2 as index. I want to create a loop that does the same for each dataframe. The code should work with any dataframe.
My code
for (i in 1:3){
p<-as.name(paste("d", i, sep = ""))%>%
ggplot(aes(x=X1, y=value, colour=as.factor(X2)))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none")+
theme_classic2()
assign(paste("p", i, sep =""), p)
}
The function works out of the loop, but when I run the loop I get the error:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a character vector
The same error was returned when I tried:
for (i in 1:3){
p<- ggplot(as.name(paste("d", i, sep = "")), aes(x=X1, y=value, colour=as.factor(X2)))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none")+
theme_classic2()
assign(paste("p", i, sep =""), p)
}
I could not find any answer in SO.
I think it could have something to do with the paste()
inside the loop.
Hope someone can help.
Upvotes: 0
Views: 1166
Reputation: 7626
I'm not sure what you're asking, and whether this route is the way to go about it. If you're looking to make three plots then looping is one way. If you substitute as.name
for get
then it should work:
d1 <- tibble(a = 1:10, b = 1:10)
d2 <- tibble(a = 10:1, b = 1:10)
d3 <- tibble(a = 5, b = 1:10)
for (i in 1:3){
p <- get(paste("d", i, sep = ""))%>%
ggplot(aes(x=X1, y=value, colour=as.factor(X2)))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none") +
theme_classic2()
assign(paste("p", i, sep =""), p)
}
Alternatively a tidier way to do it is to combine dataframes into an iterable list:
l <- list(d1, d2, d3)
for (i in 1:3){
p<-l[i][[1]]%>%
ggplot(aes(x=a, y=b))+
labs(title =paste("Plot", i, sep =" "), x = "X axis", y = "value")+
geom_line()+
theme(legend.position="none") +
theme_classic2()
assign(paste("p", i, sep =""), p)
}
This will iterate through the three dataframes and produce the graphs. I've demonstrated here with a random dataframe - if this doesn't work you then it's a good idea to post a sample dataset for further answers to try and use.
However, if you're aiming to plot three lines on the one graph, then it'd be best to combine these into a single dataframe, with the 'X1`, 'X2' and 'X3' values as a grouping column. But I'm not sure what your data looks like to do this. Can you post a sample?
Upvotes: 1