Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save plots inside a folder?

Tags:

r

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)
like image 934
maximusdooku Avatar asked Feb 18 '15 19:02

maximusdooku


1 Answers

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")
like image 184
Arthur Yip Avatar answered Oct 06 '22 00:10

Arthur Yip