# Add ggplot to a LaTeX document

In this post I will show you how you can add ggplots from R to LateX. The ggplot2 package in R really excels at producing beatiful graphs and plots. IDE’s such as RStudio also does a decent job of exporting ggplot2 graphs to png, which then can be imported in to your LaTeX document using an \includegraphics tag. However, it is with R also possible to save your file as vector graphics using TikZ. I will in this post show you how this can be achieved.

#### In R

We start out producing a simple bar chart in R using ggplot2:

library(ggplot2)

mtcars$cyl <- factor(mtcars$cyl,levels=c(4,6,8),
labels=c("4cyl","6cyl","8cyl"))

Plot <- ggplot(data = mtcars, aes(x = wt, y = mpg, color = cyl)) + geom_point() +
geom_smooth(method="lm") +
labs(main="Regression of MPG on Weight",
xlab="Weight", ylab="Miles per Gallon")


Which will give us this:

Find more examples on cran.

We could now just hit the export button save as image, define a resolution and be done with it. However, We could also convert this graph into vector graphics. This means that the graphics won’t get rendered before we produce our PDF file in LaTeX. This has the advantage that you can scale the graphic up and down as much as you like without comprimising the quality.  We can achieve this using a package in R called TikzDevice. We install and load TikZDevice as we would any other package in R:

installpackages("TikzDevice")
library(tikzDevice)


We then initialize the TikzDevice, output the plot and finally, we tell the program to shut off the TikzDevice again. This is done with three console commands:

tikz('plot1.tex',width=3.5, height=3)
Plot
dev.off()


#### In LaTeX

This creates a LaTeX file called plot1.tex. If you didn’t output it to your LaTeX working directory copy or move it there now. In our LaTeX document we first add the tikz package to the preamble, i.e the section that comes before \begin{document}:

\usepackage{tikz}


In the document we can then add the plot using the following code:

\begin{figure}[ht]
\centering
\input{plot1.tex}
\caption{Some Meaningful Caption}
\end{figure}


Depending on how large you want your graph to be you might want to change the height and width setting. It is also possible to scale the graphic in LaTeX by embedding the input command in a scalebox like this:

\scalebox{0.5}{\input{plot1.tex}}


But note that this will only scale the graphics not the text. This you would need to do in R, for example using:

theme_set(theme_gray(base_size = 10))


If you’re feeling adventurous you could also make any changes directly in the TikZ code. Just remember that if you make changes to the graph in R and do another export you’d have to make the same edits to the TikZ code again. Regardless of the method we now have a high quality graph embedded in our LaTeX document.

This site uses Akismet to reduce spam. Learn how your comment data is processed.