juhariis
juhariis

Reputation: 548

Embedding ggplot into knitr document fails

I'm creating a document using R-Studio / Knit and want to organize my work by creating graphics and tables etc before using them in the a document part, e.g.

mygraph1 <- ggplot(<whatever is needed>)

```
In this document I want the graphs shown after this line

`r mygraph1`

and before this
```{r, echo=FALSE}

but what I get is an error message

Error in vapply(x, format_sci_one, character(1L),..., USE.NAMES=FALSE) : Values must be length 1, but FUN(X[[1]]) result is 3 Calls: ... paste -> hook .inline.hook -> format_sci -> vapply Error in unlockBinding("params",) : no binding for "params" Calls : -> do.call -> unlockBinding Execution halted

(I hope I was able to copy the error message right, seems not yet found copy/paste from R Markdown window)

A way to resolve this is to output the graphs into png files instead in a previous part of the script and then link to the pngs.. But is there any other / more elegant way to do this?

Updated with a real sample below but using plot instead as it produces the same effect (and is quicker for me to demonstrate)

```{r setup, include=FALSE}

library(knitr)
n  <- 5
df <- data.frame(x=seq(1,n),y=rnorm(n))
df_kable <- kable(df)
df_plot <- plot(df)

```

## My chapter 

Tabular data works fine like this embedded in text

`r df_kable`

and it would be so cool if plot etc would work the same way as well.. 

`r ds_plot`

But looks it does not. So sad..

```{r echo=FALSE}

Upvotes: 3

Views: 4046

Answers (1)

Peter
Peter

Reputation: 7780

Graphics should be rendered in chunks, not in-line code. Here is an example .Rmd file and the resulting .html output.

---
title: Embedding ggplot into knitr document fails
---

We will generate a graphic in the following chunk.
```{r}
library(ggplot2)

mtcars_ggplot <-
  ggplot(mtcars) +
  aes(x = wt, y = mpg) +
  geom_point() +
  stat_smooth()
```

In-line code is great for things like summary statistics.  The mean miles per gallon for the `mtcars` data set is `r mean(mtcars$mpg)`.

In-line code is not good for graphics, as you know.  

Instead, use a chunk.  This will also allow you to control how the graphic is
rendered in your final document.

```{r show_figure, fig.width = 3, fig.height = 3}
mtcars_ggplot
```

enter image description here

Upvotes: 4

Related Questions