Removing borders around ggplot2 graphs

Recently I was participating in the 30DayMapChallenge where people were invited to make a map based on a different daily theme for one whole month.

When making a geographical map, or any other visualization where I wanted to use a forced coordinate system), choosing the right aspect ratio to save my graphics has always been challenging. Lately, when participating in the map challenge, CΓ©dric Scherer made me realize that I was really struggling with white borders around my plots when it came the time to export them. He was right! :smile:

The problem with choosing the right aspect ratio

Let’s make a simple map of the USA to illustrate the problem. In a markdown document, the generated graph looks good (i.e.Β no extra border) because knitr is taking care of this for me (more on that later).

# Load the US shapefile
states <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE))

p <- states %>%
  ggplot() +
  geom_sf(size = 0.25) + #<<
  coord_sf(crs = 102008) +
  theme(
    panel.border = element_blank(),
    axis.text = element_blank(),
    panel.grid = element_blank(),
    axis.ticks = element_blank(),
    plot.background = element_rect(fill = "#3c3c3c"),
    panel.background = element_rect(fill = "#3c3c3c")
  )

p

When it comes time to save my plots, I usually use the PDF format file unless they contain too much point. In that case, I will use the PNG format. When saving a graph in a file, however, it is difficult to find the right aspect ratio when using coordinate system that forces a specified ratio between the physical representation of data units on the axes (ex.: coord_fixed(), geom_sf() or coord_equal()). To visualize the problem, I will save the previous plot using two different aspect ratios and then import them in my document to show you the difficulty of finding the right aspect ratio.

Aspect ratio of 7/4

Choosing an aspect ratio of 7/4 creates white borders on the sides of the plot.

Aspect ratio of 6/7

Choosing an aspect ratio of 6/7 creates white borders at the bottom and the top of the plot.

As it can be seen in the two figures above, there are two large white borders located either on the sides or above/below of the graph. It is because I have used geom_sf() which set automatically the aspect ratio of the plot to respect the chosen geographical coordinate system. Of course, I could play around with trials and errors to find the best width and hight to use to save my plot.

But wait! There is a much better way to do it! :smirk: Actually, I found out there was a hidden gem in knitr that allows cropping (using either pdfcrop or convert functions) to remove borders around an image. In fact, this is the function that is used to automatically remove borders around images when knitting an R Markdown document in R (see the initial plot of this post without borders). The function knitr::plot_crop(x) (where x is the filename of the plot to be cropped) will trim any existing images on your hard drive.

First, let’s create our plot in PDF format and use knitr::plot_crop() to remove the borders.

pdf_file <- "../post/2019-12-20-removing-borders-around-ggplot2-graphs.en_files/fig_border.pdf"

ggsave(
  pdf_file,
  device = cairo_pdf,
  width = 5.51,
  height = 4.68
)

knitr::plot_crop(pdf_file)
#> [1] "../post/2019-12-20-removing-borders-around-ggplot2-graphs.en_files/fig_border.pdf"

At this point, the borders have been removed from the original PDF. But what if you want to export this PDF into a bitmap image? This can be achieved using a combination of pdftools::pdf_render_page() and png::writePNG(). pdftools::pdf_render_page() will take the filename of a PDF file and render into a raw bitmap array whereas png::writePNG() will actually save the bitmap into a file.

png_file <- "../post/2019-12-20-removing-borders-around-ggplot2-graphs.en_files/fig_border_cropped.png"

bitmap <- pdftools::pdf_render_page(pdf_file, dpi = 600)
png::writePNG(bitmap, png_file)

Bang! No more borders around our plot :ok_hand:

Session info

#> ─ Session info ───────────────────────────────────────────────────────────────────────────────────────────────────────
#>  setting  value                       
#>  version  R version 4.0.0 (2020-04-24)
#>  os       Linux Mint 19.3             
#>  system   x86_64, linux-gnu           
#>  ui       X11                         
#>  language en_CA:en                    
#>  collate  en_CA.UTF-8                 
#>  ctype    en_CA.UTF-8                 
#>  tz       America/Montreal            
#>  date     2020-06-02                  
#> 
#> ─ Packages ───────────────────────────────────────────────────────────────────────────────────────────────────────────
#>  package     * version    date       lib source                                 
#>  askpass       1.1        2019-01-13 [1] CRAN (R 4.0.0)                         
#>  assertthat    0.2.1      2019-03-21 [1] CRAN (R 4.0.0)                         
#>  backports     1.1.7      2020-05-13 [1] CRAN (R 4.0.0)                         
#>  blob          1.2.1      2020-01-20 [1] CRAN (R 4.0.0)                         
#>  blogdown      0.19       2020-05-22 [1] CRAN (R 4.0.0)                         
#>  bookdown      0.19       2020-05-15 [1] CRAN (R 4.0.0)                         
#>  broom         0.5.6      2020-04-20 [1] CRAN (R 4.0.0)                         
#>  callr         3.4.3      2020-03-28 [1] CRAN (R 4.0.0)                         
#>  cellranger    1.1.0      2016-07-27 [1] CRAN (R 4.0.0)                         
#>  class         7.3-16     2020-03-25 [3] CRAN (R 4.0.0)                         
#>  classInt      0.4-3      2020-04-07 [1] CRAN (R 4.0.0)                         
#>  cli           2.0.2      2020-02-28 [1] CRAN (R 4.0.0)                         
#>  colorspace    1.4-1      2019-03-18 [1] CRAN (R 4.0.0)                         
#>  crayon        1.3.4.9000 2020-05-06 [1] Github (r-lib/crayon@dcf6d44)          
#>  DBI           1.1.0      2019-12-15 [1] CRAN (R 4.0.0)                         
#>  dbplyr        1.4.4      2020-05-27 [1] CRAN (R 4.0.0)                         
#>  desc          1.2.0      2018-05-01 [1] CRAN (R 4.0.0)                         
#>  devtools      2.3.0      2020-04-10 [1] CRAN (R 4.0.0)                         
#>  digest        0.6.25     2020-02-23 [1] CRAN (R 4.0.0)                         
#>  dplyr       * 1.0.0      2020-05-29 [1] CRAN (R 4.0.0)                         
#>  e1071         1.7-3      2019-11-26 [1] CRAN (R 4.0.0)                         
#>  ellipsis      0.3.1      2020-05-15 [1] CRAN (R 4.0.0)                         
#>  evaluate      0.14       2019-05-28 [1] CRAN (R 4.0.0)                         
#>  extrafont     0.17       2014-12-08 [1] CRAN (R 4.0.0)                         
#>  extrafontdb   1.0        2012-06-11 [1] CRAN (R 4.0.0)                         
#>  fansi         0.4.1      2020-01-08 [1] CRAN (R 4.0.0)                         
#>  farver        2.0.3      2020-01-16 [1] CRAN (R 4.0.0)                         
#>  forcats     * 0.5.0      2020-03-01 [1] CRAN (R 4.0.0)                         
#>  fs            1.4.1      2020-04-04 [1] CRAN (R 4.0.0)                         
#>  generics      0.0.2      2018-11-29 [1] CRAN (R 4.0.0)                         
#>  ggplot2     * 3.3.1      2020-05-28 [1] CRAN (R 4.0.0)                         
#>  ggpmthemes  * 0.0.1      2020-04-25 [1] Github (PMassicotte/ggpmthemes@6376800)
#>  glue          1.4.1      2020-05-13 [1] CRAN (R 4.0.0)                         
#>  gtable        0.3.0      2019-03-25 [1] CRAN (R 4.0.0)                         
#>  haven         2.3.1      2020-06-01 [1] CRAN (R 4.0.0)                         
#>  hms           0.5.3      2020-01-08 [1] CRAN (R 4.0.0)                         
#>  htmltools     0.4.0      2019-10-04 [1] CRAN (R 4.0.0)                         
#>  httr          1.4.1      2019-08-05 [1] CRAN (R 4.0.0)                         
#>  jsonlite      1.6.1      2020-02-02 [1] CRAN (R 4.0.0)                         
#>  KernSmooth    2.23-16    2019-10-15 [3] CRAN (R 4.0.0)                         
#>  knitr         1.28       2020-02-06 [1] CRAN (R 4.0.0)                         
#>  lattice       0.20-41    2020-04-02 [3] CRAN (R 4.0.0)                         
#>  lifecycle     0.2.0      2020-03-06 [1] CRAN (R 4.0.0)                         
#>  lubridate     1.7.8      2020-04-06 [1] CRAN (R 4.0.0)                         
#>  magrittr      1.5        2014-11-22 [1] CRAN (R 4.0.0)                         
#>  maps          3.3.0      2018-04-03 [1] CRAN (R 4.0.0)                         
#>  memoise       1.1.0      2017-04-21 [1] CRAN (R 4.0.0)                         
#>  modelr        0.1.8      2020-05-19 [1] CRAN (R 4.0.0)                         
#>  munsell       0.5.0      2018-06-12 [1] CRAN (R 4.0.0)                         
#>  nlme          3.1-147    2020-04-13 [3] CRAN (R 4.0.0)                         
#>  pdftools      2.3.1      2020-05-22 [1] CRAN (R 4.0.0)                         
#>  pillar        1.4.4      2020-05-05 [1] CRAN (R 4.0.0)                         
#>  pkgbuild      1.0.8      2020-05-07 [1] CRAN (R 4.0.0)                         
#>  pkgconfig     2.0.3      2019-09-22 [1] CRAN (R 4.0.0)                         
#>  pkgload       1.1.0      2020-05-29 [1] CRAN (R 4.0.0)                         
#>  png           0.1-7      2013-12-03 [1] CRAN (R 4.0.0)                         
#>  prettyunits   1.1.1      2020-01-24 [1] CRAN (R 4.0.0)                         
#>  processx      3.4.2      2020-02-09 [1] CRAN (R 4.0.0)                         
#>  ps            1.3.3      2020-05-08 [1] CRAN (R 4.0.0)                         
#>  purrr       * 0.3.4      2020-04-17 [1] CRAN (R 4.0.0)                         
#>  qpdf          1.1        2019-03-07 [1] CRAN (R 4.0.0)                         
#>  R6            2.4.1      2019-11-12 [1] CRAN (R 4.0.0)                         
#>  Rcpp          1.0.4.6    2020-04-09 [1] CRAN (R 4.0.0)                         
#>  readr       * 1.3.1      2018-12-21 [1] CRAN (R 4.0.0)                         
#>  readxl        1.3.1      2019-03-13 [1] CRAN (R 4.0.0)                         
#>  remotes       2.1.1      2020-02-15 [1] CRAN (R 4.0.0)                         
#>  reprex        0.3.0      2019-05-16 [1] CRAN (R 4.0.0)                         
#>  rlang         0.4.6      2020-05-02 [1] CRAN (R 4.0.0)                         
#>  rmarkdown     2.2        2020-05-31 [1] CRAN (R 4.0.0)                         
#>  rprojroot     1.3-2      2018-01-03 [1] CRAN (R 4.0.0)                         
#>  rstudioapi    0.11       2020-02-07 [1] CRAN (R 4.0.0)                         
#>  Rttf2pt1      1.3.8      2020-01-10 [1] CRAN (R 4.0.0)                         
#>  rvest         0.3.5      2019-11-08 [1] CRAN (R 4.0.0)                         
#>  scales        1.1.1      2020-05-11 [1] CRAN (R 4.0.0)                         
#>  sessioninfo   1.1.1      2018-11-05 [1] CRAN (R 4.0.0)                         
#>  sf          * 0.9-4      2020-06-01 [1] Github (r-spatial/sf@2ca6483)          
#>  stringi       1.4.6      2020-02-17 [1] CRAN (R 4.0.0)                         
#>  stringr     * 1.4.0      2019-02-10 [1] CRAN (R 4.0.0)                         
#>  testthat      2.3.2      2020-03-02 [1] CRAN (R 4.0.0)                         
#>  tibble      * 3.0.1      2020-04-20 [1] CRAN (R 4.0.0)                         
#>  tidyr       * 1.1.0      2020-05-20 [1] CRAN (R 4.0.0)                         
#>  tidyselect    1.1.0      2020-05-11 [1] CRAN (R 4.0.0)                         
#>  tidyverse   * 1.3.0.9000 2020-06-02 [1] Github (tidyverse/tidyverse@8a0bb99)   
#>  units         0.6-6      2020-03-16 [1] CRAN (R 4.0.0)                         
#>  usethis       1.6.1      2020-04-29 [1] CRAN (R 4.0.0)                         
#>  vctrs         0.3.1      2020-06-02 [1] Github (r-lib/vctrs@504ec96)           
#>  withr         2.2.0      2020-04-20 [1] CRAN (R 4.0.0)                         
#>  xfun          0.14       2020-05-20 [1] CRAN (R 4.0.0)                         
#>  xml2          1.3.2      2020-04-23 [1] CRAN (R 4.0.0)                         
#>  yaml          2.2.1      2020-02-01 [1] CRAN (R 4.0.0)                         
#> 
#> [1] /home/filoche/R/x86_64-pc-linux-gnu-library/4.0
#> [2] /usr/local/lib/R/site-library
#> [3] /usr/local/lib/R/library

Comments