I use R to analyse data, ggplot to create plots, tikzDevice to print them and finally latex to create a report. THe problem is that large plots with many points fail due to the memory limit of latex. I found here https://github.com/yihui/tikzDevice/issues/103 a solution that rasterises the plot before printing the tikz file, which allows printing the points and the text individually.
require(png)
require(ggplot2)
require(tikzDevice)
## generate data
n=1000000; x=rnorm(n); y=rnorm(n)
## first try primitive
tikz("test.tex",standAlone=TRUE)
plot(x,y)
dev.off()
## fails due to memory
system("pdflatex test.tex")
## rasterise points first
png("inner.png",width=8,height=6,units="in",res=300,bg="transparent")
par(mar=c(0,0,0,0))
plot.new(); plot.window(range(x), range(y))
usr <- par("usr")
points(x,y)
dev.off()
# create tikz file with rasterised points
im <- readPNG("inner.png",native=TRUE)
tikz("test.tex",7,6,standAlone=TRUE)
plot.new()
plot.window(usr[1:2],usr[3:4],xaxs="i",yaxs="i")
rasterImage(im, usr[1],usr[3],usr[2],usr[4])
axis(1); axis(2); box(); title(xlab="x",ylab="y")
dev.off()
## this works
system("pdflatex test.tex")
## now with ggplot
p <- ggplot(data.frame(x=x, y=y), aes(x=x, y=y)) + geom_point()
## what here?
In this example the first pdflatex
fails. The second succeeds due to the rasterisation.
How can I apply this using ggplot?
here's a proof-of-principle to illustrate the steps that would be involved. As pointed out in the comments it's not recommendable or practical, but could be the basis of a lower-level implementation.
we can zoom in and check that the text is vector-based while the layer is (here low-res for demonstration) raster.
ok, I will write it here because it was too big for the comment box. Instead of adding the rasterised points to a nw plot with new scales you can actually replace the original grob with the rasterised grob by
g$grobs[[6]]$children[[3]] <- rasterGrob(rl)
. The problem is that it doesn't scale, so you have to know the size of the final image before. Then you can sue sth like this:And then use it with
The problem remains the ID of the grob you want to rasterise. I didn't figure out a good way to find the correct one automatically. It depends on which layers you add to the plot.