Skip to content

Instantly share code, notes, and snippets.

@slowkow
Created October 26, 2018 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slowkow/9c42d5121f5e8620f7a35c071053dcc4 to your computer and use it in GitHub Desktop.
Save slowkow/9c42d5121f5e8620f7a35c071053dcc4 to your computer and use it in GitHub Desktop.
flatten_points <- function(plot, width = 10, height = 5, dpi = 200) {
is_geom_point <- sapply(plot$layers, function(layer) {
"GeomPoint" %in% class(layer$geom)
})
plot_flat <- plot + ggplot2::theme_void()
plot_vector <- plot
plot_flat$layers <- plot$layers[is_geom_point]
plot_vector$layers <- plot$layers[!is_geom_point]
filename <- tempfile(fileext = ".png")
ggplot2::ggsave(
filename = filename,
plot = plot_flat,
device = "png"
# units = "in",
# width = width,
# height = height,
# dpi = dpi
)
img <- png::readPNG(filename)
unlink(filename)
built <- ggplot2::ggplot_build(plot = plot_vector)
range.values <- c(
built$layout$panel_params[[1]]$x.range,
built$layout$panel_params[[1]]$y.range
)
plot_vector +
ggplot2::annotation_raster(
img,
xmin = range.values[1],
xmax = range.values[2],
ymin = range.values[3],
ymax = range.values[4]
)
}
library(ggplot2)
d <- data.frame(
x = rnorm(n = 1000),
y = rnorm(n = 1000)
)
p <- ggplot(d, aes(x, y)) +
geom_point()
flatten_points(p, width = 5, height = 4, dpi = 300)
ggsave(
plot = flatten_points(p, width = 5, height = 3),
filename = "temp.svg",
width = 10,
height = 5
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment