Consider the following MWE

#+begin_src python :session :results file
import matplotlib
import matplotlib.pyplot as plt
'myfig.pdf' # return this to org-mode


How can I add a caption (and maybe also name) to the generated results block that contain a figure?

  • You could name the block using #+name: generate_image for example, then use #+caption: image caption and on the next line #+call: generate_image. I think you will also need to place the Babel source block headers in the #+call: line instead of the original block (and make the original output nothing via #+header: results none). – wvxvw May 5 '15 at 13:41
  • Sounds plausible. Could you turn it into an example? I'm not sure I understand the comment completely. – Dror Atariah May 5 '15 at 13:58
  • @mankoff, ah, right, you could label the #+results, I didn't think of it. Anyways, I'm going to add an example, just for the sake of diversity. – wvxvw May 5 '15 at 15:19
#+NAME: fig:org_fig
#+BEGIN_SRC python :results file :exports results :session org_org
plt.savefig('org.png', transparent=True, bbox_inches='tight')
#+CAPTION: Org Fig
#+LABEL: fig:org_fig
#+ATTR_LATEX: :width 0.5\textwidth
#+RESULTS: fig:org_fig

Order is important. Putting +#NAME or +CAPTION higher/lower may cause issues.

  • Can this work also for HTML export? – Dror Atariah May 5 '15 at 20:28
  • This works also for HTML. – Dror Atariah May 6 '15 at 14:45
  • The problem with this approach is that next time Ctl-c Ctl-c is used to evaluate the code block, it won't recognize that the existing #+RESULTS block is associated with the code block anymore, and it will generate a new result block - without the caption or label on it - and push the existing one down the page. – Ken Williams Jan 6 '16 at 23:07
  • @Ken not in my version of Org (8.3.2). – mankoff Jan 7 '16 at 11:28
  • @mankoff Sorry, you're right, I was doing the labeling wrong. – Ken Williams Jan 7 '16 at 19:13

Here's the example I had in mind:

* Example
  #+name: example_plot
  #+begin_src python :exports none
    import matplotlib
    import matplotlib.pyplot as plt

    fig = plt.figure(figsize = (3, 2))
    plt.plot([1, 3, 2])

* Example output
  #+caption: This is an example plot
  #+label: example-label
  call_example_plot[:session]()[:results file :exports results]

Exported to LaTeX it produces:

% Created 2015-05-05 Tue 18:53
  pdfcreator={Emacs (Org mode 8.2.2)}}


\section{Example output}
\caption{\label{example-label}This is an example plot}
% Emacs (Org mode 8.2.2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.