2

I am using tikzDevice package to obtain Latex-friendly graphs in R. I am having trouble in removing excessive white spaces from top and bottom of the graph below: Example

I have tried using par(mar) but it does not seem to work with ggplot2. Also, theme(plot.margins) seems to unresponsive as well. The white space is introduced as I try to alter the aspect ratio of the figure with theme(aspect.ratio). Any suggestions? Thanks!

EDIT: Here is a MWE:

library(tikzDevice)
library(reshape2)
x = seq(0,1,0.1)
y1 = x^2+2*x+7
y2= x^+2*x+2

df = data.frame(x,y1,y2)
df <- melt(df, id.vars=c("x"))
names(df) <- c("x","$latex~Name$","value")
plot <- ggplot(df,aes(x=x,y=value,color=`$latex~Name$`,group=`$latex~Name$`)) + geom_line() +
  theme(aspect.ratio = 0.4)
plot

tikzDevice(file="mweTex.tex")
plot
dev.off()
2

1 Answer 1

5

The problem seems to be caused by some tikz statements that affect the bounding box of the image. Since there doesn't seem to be any option in tikzDevice for minimizing whitespace, I had to think of something else. I managed to fix the generated tikz file by adding the following R code at the end of your MWE:

# remove all lines that invisibly mess up the bounding box
lines <- readLines(con="mweTex.tex")
lines <- lines[-which(grepl("\\path\\[clip\\]*", lines,perl=F))]
lines <- lines[-which(grepl("\\path\\[use as bounding box*", lines,perl=F))]
writeLines(lines,con="mweTex.tex")

I've tested it on your MWE:

result image The left image is without the fix, the right image is with the fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.