Home > Back-end >  Print a plot I have saved in the environment anywhere in Rmarkdown
Print a plot I have saved in the environment anywhere in Rmarkdown

Time:01-12

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.

CodePudding user response:

here, check out this link: output

CodePudding user response:

An easy and simple option is to wrap the plot command within a function and then call the function wherever you like,

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

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

## R Markdown

```{r pressure}
plot_later <- function() {
  plot(pressure)
}
```

Now we can plot the figure here.

```{r}
plot_later()
```

printing the plot at arbitrary place


  • Related