How can I plot a "ggplot" figure on a .PDF using MarkDown?

ggplot2

#1

Hi, I am trying to knit a PDF in which I should plot some figures created using ggplot2.

Usually, I plot figures using this script

```{r pressure, echo=FALSE}
plot(pressure)

Now, I would like to plot on a PDF a ggplot figure that I created and named in a work script.r

I tryed this way:

```{r chlorophyll, echo=FALSE}
require(ggplot2)
gg1

then, the PDF is not created and I have an error:

Error in eval(expr, envir, enclos) : object 'gg1' not found
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted

How can I ask Markdown to plot ggplot figures I have already created?

Thank you


#2

This does not seem like a Rmarkdown issue, but rather one of learning to use ggplot2. You should check out the data visualization chapter of R for data science as a good starting point


#3

I’m not sure whether you are asking about how to write the code for a ggplot. If so:

library(ggplot2)

ggplot(pressure, aes(x = temperature, y = pressure)) + 
  geom_point()

http://ggplot2.tidyverse.org/

You can then knit this just like you would other plots.


#4

I apologise for my previous question, I hope I am more precise now.


#5

If you have generated gg1 outside the .Rmd file then it won’t recognise the object.

There are a few ways to get around this:

  • Generate the gg1 object in a code chunk or call the original script via e.g. source("gg1_script.R")
  • Add the output of gg1 (e.g. a png file) via knitr::include_graphics
  • Run rmarkdown::render("file.Rmd") in the environment where gg1 exists (I haven’t tried this for pdf, but I use this option for html successfully)

#6

In the spirit of knitr::include_graphics, @zevross’ post, below, has some good pointers.


#7

You can assign the ggplot as an object in the Rmd document (or even in a separate script you source from the Rmd file, as long as it is in the same R environment)

library(ggplot2) 

my_plot <- ggplot(pressure, aes(x = temperature, y = pressure)) +   
  geom_point()

and then print it in the place & time you need

print(my_plot)

Sometimes I find it advantageous to make a big “init” chunk of code at the beginning of the Rmd that does all the work, and then use the results later on in text.

This happens mostly when I have the code already done from an exploratory phase, and want to cobble together a quick & dirty report without rewriting my code. Not the most elegant solution, but it works when time is of an issue.