Prevent PDF storing invisible map data

Viewed 106

When saving maps as PDF in R, the pdf still stores map data (polygons, polylines) that are in the object being plotted but outside the visible area of the map. Is there any way to prevent that?

library(ggplot2)
library(tidyverse)


continent <- map_data('world') %>%
  filter(region %in% c("Canada", "USA")) %>% fortify()

pdf(file = ".../Results/My Plot.pdf", width=8, height=4)
# pdf() or ggsave() give the same results

ggplot()+ 
  geom_polygon(data = continent, aes(x = long, y = lat, group=group),
               fill="lightgray", colour = NA) +
  coord_sf(xlim = c(-82, -57), ylim = c(28, 43), expand = FALSE)

dev.off()

The map as seen in the pdf

PDF map

The map in Inkscape, with the main plot "ungrouped" (as in https://inkscape-manuals.readthedocs.io/en/latest/grouping.html - ungrouping the main part of the plot 2 or 3 times). Inkscape map

1 Answers

One solution would be to remove the unwanted data point from continent.

A quick (and somewhat dirty) workaround would be to save the plot as a png and convert it to a PDF:

#library
library(tidyverse)
library(maps)
library(grid)
library(gridExtra)
library(png)

# generate data
continent <- map_data('world') %>%
  filter(region %in% c("Canada", "USA")) %>% fortify()

#make plot
plot <- ggplot()+ 
  geom_polygon(data = continent, aes(x = long, y = lat, group=group),
               fill="lightgray", colour = NA) +
  coord_sf(xlim = c(-82, -57), ylim = c(28, 43), expand = TRUE, clip="on")

# plot plot
plot

#save plot
ggsave("test.png",dpi=500)
#> Saving 7 x 5 in image


# load png and make a raster
rasterGrob(readPNG("test.png", native = FALSE),
           interpolate = FALSE) -> go

# print PDF
go1 <- list(go)
pdf("test.pdf")
do.call(grid.arrange, c(go1, ncol = 1))
dev.off()

Created on 2021-11-05 by the reprex package (v2.0.1)

PDF in Inkscape after using "ungroup" multiple times (does not bring back the data outside the plot): enter image description here

Related