I am working from an R project and have files arranged in folders: Data, Script, Output_Files. I have created a figure using grid.arrange and ggplot and want to save it to the Output_Files folder using here. It will save if I save it to the default directory which is the scripts folder but I need to save it to Output_Files as I have many of these plots.
# Load packages
library("ggplot2")
library("gridExtra")
library(here)
#> here() starts at C:/Users/lcronin/AppData/Local/Temp/RtmpkxhARY/reprex-561818772666-cilia-stag
set.seed(123)
# Create data frames
data1 <- data.frame(x = rnorm(50, mean = 10, sd = 2) , y = rnorm(50, mean = 5, sd = 1) )
data2 <- data.frame(x = rnorm(40, mean = 10, sd = 2) , y = rnorm(40, mean = 5, sd = 1) )
data3 <- data.frame(x = rnorm(60, mean = 10, sd = 2) , y = rnorm(60, mean = 5, sd = 1) )
#Create three ggplot2 plots
p1<-ggplot(data1, aes(x = x, y = y)) +
geom_point()
p2<-ggplot(data2, aes(x = x, y = y)) +
geom_point()
p3<-ggplot(data3, aes(x = x, y = y)) +
geom_point()
# Arrange in one figure
CombPlot<-grid.arrange(p1, p2, p3, ncol = 3)
# Save the combined plots in one figure
ggsave("Combination_Plot.jpg", CombPlot)
#> Saving 7 x 5 in image
ggsave(CombPlot, here("Output_Files", "Combination_Plot.jpg"))
#> Error in `ggsave()`:
#> ! `filename` must be a single string, not a <gtable/gTree/grob/gDesc> object.
# in stead of
ggsave(CombPlot, here("Output_Files", "Combination_Plot.jpg"))
# use the filename first, then the ggplot object
ggsave(here("Output_Files", "Combination_Plot.jpg"),CombPlot)