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.
require(png)
require(ggplot2)
require(tikzDevice)
n=100;
d <- data.frame(x=rnorm(n), y=rnorm(n), z=rnorm(n))
p <- ggplot(d, aes(x=x, y=y, colour=z, size=z, alpha=x)) + geom_point()
## draw the layer by itself on a png file
library(grid)
g <- ggplotGrob(p)
# grid.newpage()
gg <- g$grobs[[6]]$children[[3]]
gg$vp <- viewport() # don't ask me
tmp <- tempfile(fileext = "png")
png(tmp, width=10, height=4, bg = "transparent", res = 30, units = "in")
grid.draw(gg)
dev.off()
## import it as a raster layer
rl <- readPNG(tmp, native = TRUE)
unlink(tmp)
## add it to a plot - note that the positions match,
## but the size can be off unless one ensures that the panel has the same size and aspect ratio
ggplot(d, aes(x=x, y=y)) + geom_point(shape="+", colour="red") +
annotation_custom(rasterGrob(rl, width = unit(1,"npc"), height=unit(1,"npc"))) +
geom_point(aes(size=z), shape=1, colour="red", show.legend = FALSE)
## to illustrate the practical use, we use a blank layer to train the scales
## and set the panel size to match the png file
pf <- ggplot(d, aes(x=x, y=y)) + geom_blank() +
annotation_custom(rasterGrob(rl, width = unit(1,"npc"), height=unit(1,"npc"), interpolate = FALSE))
tikz("test.tex", standAlone=TRUE)
grid.draw(egg::set_panel_size(pf, width=unit(10, "cm"), height=unit(4, "cm")))
dev.off()
system("lualatex test.tex")
system("open test.pdf")
we can zoom in and check that the text is vector-based while the layer is (here low-res for demonstration) raster.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…