R + Org-mode: how to avoid naming plot files?

Great question, and a similar one (plus some extra stuff) came up on the Org-mode mailing list back in September. The original question is here, and a sketch of a possible solution lies in the final message of the thread here (see #1, the other items are about other things).


Here's another approach using an incrementor, as the use of

(org-babel-temp-file "./figure-" ".pdf")

didn't seem to work for me:

(setq i 0)
#+begin_src R :file (concat "f" (number-to-string (incf i)) ".pdf") :results output graphics :exports results
(plot (rnorm(10))
#+end_src

(setq i) only needs to be called once per session to define the variable; it can then be erased. The plots are saved to your default-directory and appear automatically when exporting the .org file to .tex using (org-latex-export-as-latex).


I improved the approach of [dardisco] to make the behavior truly automatic. Basically, the code below includes a block that creates a lisp variable that is then fed to all figure blocks.

This elisp block should be placed at the beginning of your file (before any figure block, at least).

#+name: fignumber 
#+begin_src emacs-lisp :results value silent :exports none :session 
(setq fignumber 0)
#+end_src

#+BEGIN_SRC R :results output graphics file :file (concat "figure" (number-to-string (incf fignumber)) ".pdf") :exports results :session
x <- 1:100
y <- 1:100
plot(x,y)
#+END_SRC