How to include a plot in my R/knitr document

Viewed 155

This seems like a simple problem, but I wasn't able to find a solution anywhere I looked.

I am writing a .Rnw document in R with the Knitr package, one that I intend to compile into .pdf form by the end. I want it to contain a few plots, preferably ones made with the ggplot2 package because it seems like the simplest solution. However, I cannot force R to include a plot in the final document. Instead of a graphic, the code writes "list()" in the place the plot should be at. Am I missing a package? Am I writing something wrong? Here is the relevant part of the code:

<<echo=FALSE>>=
library(ggplot2)
HDplot <- qplot(H,D)
@
\begin{figure}
\Sexpr{HDplot}
\end{figure}

(the problem isn't with the plot itself, as H and D are sets of values that can be plotted into a perfectly fine graph outside of the document)

1 Answers

Inline R expressions in \Sexpr{} cannot deal with plots. Plots need to be rendered in code chunks, e.g.,

\begin{figure}
<<echo=FALSE>>=
library(ggplot2)
HDplot <- qplot(H,D)
HDplot
@
\end{figure}

If you use the chunk option fig.cap to provide a figure caption, the figure environment will be automatically generated, e.g.,

<<echo=FALSE, fig.cap="A nice plot.">>=
library(ggplot2)
HDplot <- qplot(H,D)
HDplot
@

You can also generate the plot in a code chunk but hide it in the chunk, and display it elsewhere. Here is an example in R Markdown, but the idea is the same (use knitr::fig_chunk()): https://bookdown.org/yihui/rmarkdown-cookbook/fig-chunk.html

Related