I have 6 dataframes called "January","February","March","April","May","June" (they show the reflectance of trees). I made a list of these dataframes and then a loop function to generate multiple plots.
long_list <- c("January","February","March","April","May","June")
myplot <- function(data, title){
ggplot(data, aes(x = bands, y = reflectance, color = class, group = class)) +
geom_point(color="grey") +
geom_line () +
labs(title = title)
}
for(i in long_list){
print(myplot(get(i), i))
}
It worked; I am happy with the result.
But(!) I am not able to display all this plots in one window. I tried it with par(mfrow=c(3,2))
and myplot(long_list, col=3)
and cowplot::plot_grid()
and grid.arrange(myplot(long_list), nrow = 2, ncol = 3)
but was`t successful
How can I display these 6 generated plots in one window (col 3 and row 2)
ggplot2 has built in support for spreading data across multiple "plots" using facets. This makes it easier to achieve what I think you want. You can avoid the for loop entirely. You could be best combining all the data into a single data frame and letting ggplot handle creating the multiple plots.
I don`t know why, but I have problems with the installation of tidyverse; maybe because of the version of RStudio I use.
But I think I was not precise enough, cause my classes are tree species and not the dates. The dataframes I used to make the list are in long format. The classes are tree species (in the reduced example its class oak and class spruce) and the sensor bands range from B1 to B5. Each dataframe represents a specific month. Data looks like:
head(January)
class band reflectance
1 oak B1 182.04762
2 spruce B1 80.63158
...
3 oak B2 408.61905
4 spruce B2 183.84211
...
5 oak B3 279.85714
6 spruce B3 144.52632
... until...B5
So the ggplot function would look like:
ggplot(Janaury, aes(x = bands, y = reflectance, color = class, group = class)) +
geom_point() +
Before I convert my data into long format they looked like this in wide format:
I don't know your specific data or what exactly you want the final output to look like. You were using ggplot2 already, so presumably you have it installed. The entire tidyverse is not necessary. In almost all cases, long data format are preferred, especially for plotting with ggplot.
If you can share the data in a usable format, I am happy to try and reproduce your error and help find a solution.