I wanted to generate some plots for my thesis that would include mathematical symbols and integrate nicely into my latex document. I’ve enjoyed learning to use R’s ggplot2 package, and wanted to continue using it to generate my thesis plots, but I also wanted the plots to fit into the theme of my document. I used the package tikzDevice to achieve this. Previously I wrote a short piece on how to change the font when using ggplot but this gives a more cohesive result for latex documents.

### Example of a plot generated before and after using the tikzDevice package

**(Simple!) Plot generated using ggplot only without tikzDevice:**

**Same plot generated in my Latex document after using the tikzDevice package:**

### How to do it

- Install and load the package tikzDevice in R:
install.packages("tikzDevice") library(tikzdevice)

- To generate a .tex file for your image, use the following commands:
# Create the .tex file for your plot and set the plot dimensions tikz(file = "test.tex", width = 7, height = 6) # Insert your plot code here simple_plot <- ggplot(simple_dat, aes( x = numbers, y = squared)) simple_plot + geom_line() + # Labels to demonstrate Latex math formatting labs(x = "$\beta$", y = "$\\alpha = \\beta^2$", title = "Here's a plot of $\\alpha = \\beta^2$") + # Adjust text size if desired theme(plot.title = element_text(size = rel(0.9)), axis.title = element_text(size = rel(0.9)), axis.title.y = element_text(size = rel(0.9)), axis.title.x = element_text(size = rel(0.9))) # Close the plotting device dev.off()

- Before you can insert the latex file generated by R, you will have to insert the following command into your file preamble:
\usepackage{tikz}

- Move the .tex file generated by R to your latex project folder and insert the following at the desired location in your document to add your image:
\begin{figure} \centering \input{test.tex} \caption[My test image]{Insert caption here \label{fig:test_plot}} \end{figure}

- Compile and enjoy!