2

I create an Rmarkdown document where I would like to create a plot at the start of the document, and then print it at the end of the document.

I thought the best way to achieve this would be to save the plot in the environment and then recall it later, I save this as follows:

plot(1:5, 1:5) ; plot1 <- recordPlot()                # I create a plot and save it as plot1

This plot is saved under "Data" in the environment.

If I enter plot1 into the console, my plot is reproduced, but when I try to display it directly in Rmarkdown as follows I get the following error:

plot(plot1)

Error in xy.coords(x, y, xlabel, ylabel, log) :
  'x' is a list, but does not have components 'x' and 'y'

How I can take the plot that I saved into Data and print it anywhere I would like in my Rmarkdown document?

p.s. I know it's tempting to say to repeat the plot again later in the document, but the parameters that build the plot are subsequently altered for another part of my analysis.

Re-producible example:

x = 1


plot_later <- function() {
  plot(x)
}

plot_later()

On the left X is at 1

x = -10

plot_later()

On the left x is now at -10

X starts at 1 then changes to -10 on the Y axis, I want it to stay at the initial value of 1.

  • 1
    one of these might help: https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html – I_O Jan 11 '23 at 20:26
  • you just need to call the `plot1` object instead of passing it to `plot` function again. So just do `plot1` instead of `plot(plot1)`. – shafee Jan 12 '23 at 04:59
  • @shafee If I enter just plot1 in a code chunk in Rmarkdown, the chunk will execute, but no plot will be displayed in the Rmarkdown document – James Moore Jan 12 '23 at 09:01
  • @I_O I reviewed that link, but their method for reusing a chunk basically asks that I run that code chunk again, in my situation my variables have changed following their first use, so applying the code chunk to them again would result in a different plot altogether, what I need to do is print the plot I've already produce and saved in the environment again. – James Moore Jan 12 '23 at 09:05
  • see added answer please; the plot looks up the variable definitions from its own chunk first; if you need global variables, see e.g. https://stackoverflow.com/questions/65130393/how-to-set-global-variables-in-r-markdown – I_O Jan 12 '23 at 10:11

3 Answers3

1

here, check out this link: https://bookdown.org/yihui/rmarkdown-cookbook/fig-chunk.html

It has a lot of instructions on how to get started with rmarkdown.

Specifically answering your question:

We generate a plot in this code chunk but do not show it:

```{r cars-plot, dev='png', fig.show='hide'}
plot(cars)
```

After another paragraph, we introduce the plot:

![A nice plot.](`r knitr::fig_chunk('cars-plot', 'png')`)

Basically you have to save your graph as a variable and then call on it using the knitr::fig_chunk() function.

shafee
  • 15,566
  • 3
  • 19
  • 47
Pablo Rodriguez
  • 233
  • 1
  • 10
0

Solution based on https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html :

---
title: plot now, render later
output: html_document
---


We put some plot expression here to evaluate it later:
```{r, deja-vu, eval=FALSE}
x = 1
plot(x)
```

Here we change `x` - but only within the corresponding chunk's scope:
```{r}
x = 10
```

... moving on 


Here, we evaluate and plot the expression defined earlier; x is taken from that chunk's scope, so it still evaluates to `1`:
```{r, deja-vu, eval=TRUE}
```

output

I_O
  • 4,983
  • 2
  • 2
  • 15
  • Thanks @I_O But, if you run each code chunk individually, you'll see that your first code chunk creates and displays the plot while your third code chunk doesn't display a plot, which is the issue I am having too – James Moore Jan 12 '23 at 11:51
  • Are you speaking of the rendered document or of testing your R-markdown chunk by chunk? If the latter, see if the issue persists in the rendered document. – I_O Jan 12 '23 at 12:49
  • Thank you @I_O the issue only presents when testing my R-markdown chunk by chunk, and not in the rendered document. Is there a way to make this work when testing the document chunk by chunk? – James Moore Jan 14 '23 at 01:48
0

One option could be saving the plot as grob object using as.grob function from ggplotify and then print it elsewhere.

---
title: "Saving A Plot"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

```{r}
library(ggplotify)
library(grid)

show_captured_plot <- function(grb) {
  grid::grid.newpage()
  grid::grid.draw(grb)
}
```

```{r}
x <- 1

p <- as.grob(~plot(x))
```


Now we can plot the figure here.

```{r}
x <- 10

show_captured_plot(p)
```

printing the plot at arbitrary place


shafee
  • 15,566
  • 3
  • 19
  • 47
  • the problem with this approach is when the parameters that build the plot are subsequently altered for another part of my analysis, this will result in either not being able to build a plot, or building a plot with different values than initially used. – James Moore Jan 12 '23 at 11:59
  • I do not get the point you are making with the parameters of plot. Can you add a reproducible example in your question that showcases the problem? – shafee Jan 12 '23 at 12:06
  • I've added this as requested. – James Moore Jan 12 '23 at 12:43
  • Does the updated answer work?! – shafee Jan 15 '23 at 16:04