I have put together a simple for loop to generate a series of plots and then use grid.arrange to plot them. I have two problems:
The axes of the plots change correctly to the column names, but the same data is plotted on each graph. Having put in a breakpoint and stepped through the code it appears to be incrementing correctly so I'm not sure why.
I have set the plot aesthetic to group on year, however this produces intermediate .5 years that appear in the legend. This hasn't happened to me before.
Should all be reproducible using mtcars
.
library(ggplot2)
library(gridExtra)
result <- mtcars
for(i in 1:2) {
nam <- paste("p", i, sep = "")
assign(
nam, ggplot(result, aes(x = disp, y = results[i+4], group = gear, color = gear)) +
geom_line() +
geom_point() +
scale_colour_distiller(palette = "Dark2", direction = -1, guide = "legend") +
scale_y_continuous(name = colnames(results[i+4])) +
scale_x_continuous(name = "x")
)
}
plist <- mget(paste0("p", 1:2))
do.call(grid.arrange, plist)
You should take full advantage of
ggplot::facet_wrap
This means tidying your data to a single data frame that's interpretable to ggplot
Data
Tidy data
plot with facet_wrap
Your using results and result. And you should use aes_string and then refer to the variables by string name:
You should also avoid to make tons of assignments. Just put it all into a list()
The problem is that the plot is generated in the for loop, but evaluated in the do.call. Since
i
has changed in the for loop, both are evaluated withi = 2
. You can confirm this with:A small adjustment to your code fixes the issue:
I think trying to access the columns by their number in the
aes
mapping is confusing ggplot. This works:I would suggest iterating over the names though; this makes the code much clearer. Here's a version that does this and skips the detour around the environment: