8

This is such a basic question, but I am not able to find an answer to it.

All I want to do is to store all figures to a folder one directory inside where the R script is stored. And I don't want to use full dir, but relative directory, as I work from multiple computers.

So, I have this structure:

/code
  /Rscript1
  /inputdata
  /Rscript2 
      /figs
          fig1
          fig2

All I want to do is tell ggplot to store all figures inside "figs" folder instead of the same folder as Rscript1 and Rscript2 (i.e. "code" folder).

scatter<-function(df,x,y){
  ggplot(df, aes_string(x=x, y=y)) +
    geom_point()+
    theme_bw()+
    theme(panel.grid.major = element_line(colour = "#808080"))
}

scatter(df=dassmp,x='Oss',y='sa')+
  ggsave('fig1.png',width=6, height=4,dpi=300)
maximusdooku
  • 5,242
  • 10
  • 54
  • 94
  • 8
    I searched for happiness everywhere in the world and found it in my backward. The answer is figs/fig1.png – maximusdooku Feb 18 '15 at 20:07
  • 6
    If you want just relative paths, you'd want `ggsave("figs/fig1.png", ...)` (no leading slant). – r2evans Feb 18 '15 at 20:08
  • 1
    Sometimes also `setwd("C:/.../directory/to/location/")` and `getwd()` can be useful. R defaults to working directory and does not necessarily care about the location of the script. Wd can be changed also under Files->More in the panel in the bottom-right by default in RStudio. – puslet88 Feb 18 '15 at 20:39
  • There is an interesting package called ```here``` [https://cran.r-project.org/web/packages/here/index.html] ... very usefull for the kind of issue you are dealing with, and easy of use .. – MrSmithGoesToWashington Jul 15 '21 at 08:01

1 Answers1

10

Since you mentioned different computers, to be safe, if your code is used on different systems e.g. Windows/Mac/Linux), you should use

ggsave(path = "figs", filename = "fig1.png")

or

ggsave(filename = file.path("figs","fig1.png")

to avoid hardcoding the wrong slanting slashes.

Even better, if your project is organized differently and your R script is placed somewhere else, or you're working in a RStudio project or Git repository, you can make sure your relative file paths point to a consistent location by using the package here:

library(here)
ggsave(filename = here("figs","fig1.png")
Arthur Yip
  • 5,810
  • 2
  • 31
  • 50