Search code examples
rggplot2pdflatextikzdevice

University document class and tikzpicture generated by R's ggplot and tikzdevice


I'm using the university document class, and I guess that this class is somehow affecting the layout of the legend keys and legend labels of plots generated using R's ggplot2 and tikzDevice.

In order to reproduce this issue, please run the following R script:

require(dplyr)
require(ggplot2)
require(tikzDevice)

pi <- filter(diamonds, (cut=="Premium" | cut=="Ideal") & color<"I")
pi$cut <- factor(pi$cut)
pi$color <- factor(pi$color)

g1 <- ggplot(data=pi, aes(x=color, fill=cut, y=price)) +
  geom_violin() + theme(legend.position = "top")

setTikzDefaults(overwrite = TRUE)
preamble <- options("tikzLatexPackages") 
options("tikzLatexPackages" = c(preamble$tikzLatexPackages, "\\usepackage{amsmath}"))
tikz(file = "out.tex", width = 3, height = 2, standAlone = T )

print(g1)

dev.off()

Now, if we compile the output file of this script (out.tex) using pdflatex, we should get something like this (Please note that the legend is perfectly normal here):

enter image description here

Now, let's change the line "\documentclass[10pt]{article}" inside the output file (out.tex) to "\documentclass[pdftex]{pittetd}" and compile out.tex using pdflatex. Please note that pittetd.cls needs to be in the same directory as out.tex (or installed in your system). You will see some compiler errors, like "Missing number, treated as zero." Just ignore these errors, please, as they have nothing to do with our issue, and keep pressing Enter until the new PDF file (out.pdf) is generated. The output looks something like the following (Note the legend labels and keys are overlapping):

enter image description here

My best guess is that the problem might be some macro definition conflict between TikZ and pittetd.

Can anyone please tell me why this is happening and how to fix it?

EDIT:

In the file out.tex, if we use pittetd document class, I noticed that if I change the parameters of the tikzpicture environment, the problem gets resolved; in other words, if we change the following line:

\begin{tikzpicture}[x=1pt,y=1pt]

To:

\begin{tikzpicture}[x=1.1pt,y=1pt]

This should remove the overlap; however, it will also stretch the plot horizontally, which is undesirable. I wonder if there is a better way to solve this problem without having to use this hack (maybe by changing pittetd.cls file).


Solution

  • The font size is changing from 10pt to 12pt, so the word sizes that were evaluated by tikzDevice at 10pt are now too small, hence the clashes.

    As a side-note, I find it easier to produce pdfs externally, then include it without any rescaling in the main latex document. I find inline tikz graphs harder to debug.