0

I am trying to develop slides for a course I am teaching in Org mode compiling to a latex beamer presentation. Overall most things are working fine. But for some reason I am having trouble getting two R plots aligned. Here is how the relevant slide looks currently. The problem should be obvious.

problematic slide

Here is the code for the presentation:

#+TITLE:     my class
#+AUTHOR:    me
#+EMAIL:     [email protected]
#+BEAMER_HEADER: \institute[]{Penn State University} 
#+DATE:      
#+DESCRIPTION: 
#+KEYWORDS: 
#+LANGUAGE:  en
#+BEAMER_THEME: Boadilla
#+BEAMER_HEADER: 
#+latex_class: beamer
#+latex_compiler: pdflatex
#+LaTeX_HEADER: \usepackage{pdfpages}
#+OPTIONS: H:2 toc:t
#+BEAMER_HEADER: \AtBeginSection[]{\begin{frame}<beamer>\vfill\centering\usebeamerfont{title}\insertsectionhead\vfill\end{frame}}
#+BEAMER_HEADER: \usepackage{minted}
#+BEAMER_HEADER: \usemintedstyle{emacs}
#+STARTUP: beamer


#+begin_src R :exports none 
  library(tidyverse) 
  set.seed(123)
#+end_src

* Bayesian Statistics

** Metropolis Algorithm Example
\begin{align*}
y_i &\sim N(\beta x_i, \sigma^2) \\
\beta &\sim N(\mu, \tau^2)
\end{align*}
*** XXX                                                                                    :BMCOL:
:PROPERTIES:
:BEAMER_col: .55
:END:
#+begin_src R :exports code :session "*R*"
# Simulate some data
n <- 100 
beta <- 4.1
sigma2 <- 1.3
x <- rnorm(n)
y <- rnorm(n, mean=beta*x, 
              sd=sqrt(sigma2))
#+end_src

*** XXX                                                                                    :BMCOL:
:PROPERTIES:
:BEAMER_col: .45
:END:
#+begin_src R :exports results :session "*R*" :results graphics file :file figures/foo.pdf
plot(x,y)
#+end_src

#+RESULTS:
**  Metropolis Algorithm Example
\begin{align*}
y_i &\sim N(\beta x_i, \sigma^2) \\
\beta &\sim N(\mu, \tau^2)
\end{align*}

\tiny
#+begin_src R :exports code :session "*R*"
# For the moment we deal only with 
# simple regression (x is univariate)
log_p_tilde <- function(beta, y, x, sigma2, mu, tau2){
  loglik <- dnorm(beta, mean=mu, 
                        sd=sqrt(tau2), 
                        log = TRUE)
  loglik <- loglik + 
            sum(dnorm(y, mean=beta*x, 
                         sd=sqrt(sigma2), 
                         log=TRUE))
  return(loglik)
}

# Now the proposal function J(theta | theta^(s))
proposal <- function(beta_s, delta2){
  return( rnorm(1, mean=beta_s, sd=delta2) )
}
#+end_src
\normalsize

** Metropolis Algorithm Example
*** XXX                                                                                    :BMCOL:
:PROPERTIES:
:BEAMER_col: .5
:END:
\tiny
#+begin_src R :exports code :session "*R*" :results silent
n_samples <- 4000
beta <- rep(NA, n_samples)
# Initialize chain
beta[1] <- 0
# Create partial function to make code easier to read
lpt <- function(beta) log_p_tilde(beta, y, x, 1.3, 
                                  # Choose priors
                                  mu = 0, tau2 = 1)
# Run MCMC
for (s in 2:(n_samples+1)){
  # Propose
  beta_prop <- proposal(beta[s-1], delta2 = .1)
  
  # Compute Acceptance Ratio (log-scale)
  r <- lpt(beta_prop) - lpt(beta[s-1])
  
  # Sample uniform
  u <- runif(1, min=0, max=1)
  
  # Accept/Reject
  if (u <= exp(r)){
    beta[s] <- beta_prop
  } else {
    beta[s] <- beta[s-1]
  }
}
# Drop "Burn-in" rid of initial sample which we chose
beta <- beta[-(1:n_samples/2)]
#+end_src
\normalsize
*** XXX                                                                                    :BMCOL:
:PROPERTIES:
:BEAMER_col: .5
:END:
#+begin_src R :exports results :session "*R*" :results graphics file :file figures/beta-posterior-trace.pdf :width 3 :height 3
plot(beta)
#+end_src

#+begin_src R :exports results :session "*R*" :results graphics file :file figures/beta-posterior-density.pdf :width 3 :height 3
plot(density(beta))
#+end_src

I would greatly appreciate any help in debugging this issue!

EDIT: After reading this post Change emacs generated image size in org-mode export, I came up with the following solution (which does not work):

#+name: beta-posterior-trace
#+begin_src R :session "*R*" :file figures/beta-posterior-trace.pdf 
plot(beta)
#+end_src

#+ATTR_LATEX: :width 0.3\linewidth
#+results: beta-posterior-trace
[[file:figures/beta-posterior-trace]]

#+name: beta-posterior-density
#+begin_src R :session "*R*" :file figures/beta-posterior-density.pdf
plot(density(beta))
#+end_src

#+ATTR_LATEX: :width 0.3\linewidth
#+results: beta-posterior-density
[[file:figures/beta-posterior-density]]

Here is how that ends up looking: still not working

10
  • 1
    I don't think there is a problem: you just have too much stuff so it doesn't fit on the slide. I think you are going to have to split it up into separate slides.
    – NickD
    Sep 13, 2022 at 21:11
  • It all fits nicely when I coded in R markdown. I placed no restrictions on the size of the plots so that should not be considered in posing a solution.
    – jds
    Sep 13, 2022 at 23:47
  • The issue seems to be I am not able to modify the \includegraphics width parameter... How do I modify this in a src export block?
    – jds
    Sep 14, 2022 at 0:00
  • 2
    Does this answer your question? Change emacs generated image size in org-mode export
    – NickD
    Sep 14, 2022 at 1:04
  • 2
    You forgot the :exports results on the last two source code blocks. Also, the .pdf suffix is missing from the links. I would just delete the two links completely.
    – NickD
    Sep 15, 2022 at 20:48

2 Answers 2

1

Checking the produced .tex file shows that the two plots on the last page are produced by this code:

\begin{column}{.5\columnwidth}
\begin{center}
\includegraphics[width=0.9\linewidth]{figures7/beta-posterior-trace.pdf}
\end{center}


\begin{center}
\includegraphics[width=0.9\linewidth]{figures7/beta-posterior-density.pdf}
\end{center}
\end{column}

A little trial-and-error tweaking of the .tex file shows that width=0.6\linewidth would make both figures small enough to fit in the RH column.

There is a setting, org-latex-image-default-width, whose default value is 0.9\textwidth so you could change it. The trouble with that is that all figures would be squeezed a bit.

The standard way of changing the width of one figure for LaTeX export is to add a #+ATTR_LATEX: :width ... directive just before the image link. So if we had an image that pre-existed, we could do

#+ATTR_LATEX: :width 0.6\linewidth
[[file:figures7/beta-posterior-density.pdf]]

and that would propagate the value into the resulting \includegraphics. However, here we have plots that are dynamically produced, so we don't have the link to the figure to attach the #+ATTR_LATEX line to.

The solution is in three parts:

  • Give a name to each of the two code blocks with #+name.
  • Run each code block by hand with C-c C-c to produce a labeled #+RESULTS line (and a link to the image file but that is not the main point here).
  • Attach the #+ATTR_LATEX line to the #+RESULTS line and delete the links.

It will then look like this:

#+name: beta-plot
#+begin_src R :exports results :session "*R*" :results graphics file :file figures7/beta-posterior-trace.pdf :width 3 :height 3
plot(beta)
#+end_src

#+ATTR_LATEX: :width 0.6\linewidth
#+RESULTS: beta-plot


#+name: beta-density-plot
#+begin_src R :exports results :session "*R*" :results graphics file :file figures7/beta-posterior-density.pdf :width 3 :height 3
plot(density(beta))
#+end_src

#+ATTR_LATEX: :width 0.6\linewidth
#+RESULTS: beta-density-plot

When you export, the export happens in a temporary buffer containing a copy of the Org mode file. At that time, the code blocks will be executed and they will produce the image files (if they don't exist already), and also add the figure links after the corresponding #+RESULTS lines. That's why we had to name the code blocks: the labeled #+RESULTS lines act as place holders so that the links to the images would be put right after them (remember that's done in the temprorary copy), and the #+ATTR_LATEX lines are attached to the links (think of them as diffusing through the #+RESULTS lines). Without the names, this would not work. The export happens, the temporary copy disappears and your file looks exactly the same as before: you only have to do the manual stuff once.

1
  • I am now in a bit of a quandary: did this answer specifically answer your question in a way that the other two did not? If so, which part? I was hoping that you'd find the answer in one or the other or both of the other questions, but you accepted this one. I would rather have one definitive answer, so if you could point out what this answer contributes that the other answers do not, I will edit the other answer(s) to add this info and delete this one (you could upvote them instead of upvoting and accepting this one in that case if you felt so inclined).
    – NickD
    Sep 20, 2022 at 20:36
0

Editing the code on the relevant slide to the following seems to have worked.

#+begin_src R :exports results :session "*R*" :file figures/beta-posterior-trace.pdf 
plot(beta)
#+end_src

#+ATTR_LATEX: :width 0.65\linewidth
[[file:figures/beta-posterior-trace.pdf]]

#+begin_src R :exports results :session "*R*" :file figures/beta-posterior-density.pdf
plot(density(beta))
#+end_src

#+ATTR_LATEX: :width 0.65\linewidth
[[file:figures/beta-posterior-density.pdf]]

That said, I am not exactly sure why this particular "incantation" worked but just adding #+ATTR_LATEX: :width 0.65\linewidth above the src block directly didnt...

I am also not sure why I needed the :exports results directive but I didnt need a :results none or :results file directive

5
  • 1
    That will probably break if you delete the images and you have to recreate them by rerunning the source code blocks. Please reread the answer to the linked question carefully. There is a bunch of subtleties involved. Naming the blocks and keeping the #ATTR_LATEX ... #+RESULTS: <block name> structure intact is very important. I will undelete my answer: let's see if that helps.
    – NickD
    Sep 15, 2022 at 20:57
  • #ATTR_LATEX is an affiliated keyword: it needs to be placed just before the element that it modifies (e.g. an image, a table or a LaTeX snippet) without anything intervening (not even an empty line - except for "diffusing" across #+RESULT lines as mentioned in my answer) . And it is not applicable to a code block at all, so it is just ignored there. That's one of the subtleties I mention above.
    – NickD
    Sep 16, 2022 at 16:29
  • I guess my answer was not helpful, so I deleted it again to leave the original question/answer as the definitive one. But you might find this SO question/answer useful.
    – NickD
    Sep 19, 2022 at 2:43
  • Please don't delete! Sorry life has been hectic and I have not had consistent time to work on these lecture slides that said I was hoping to review your answer today.
    – jds
    Sep 20, 2022 at 10:15
  • OK - I undeleted it for now: I think that everything in it is in the other answer (and the SO answer that I linked to above), so let me know when you are done and I will delete it again.
    – NickD
    Sep 20, 2022 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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