Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a ggplot2 graphic with the proper aspect ratio?

Tags:

My question is about how to save a ggplot2 graph in respect with the aspect ratio. If I make a simple graphic and set the dimension of the plot with ggsave(), the plot will occupy the entire area of the saved file.

library(ggplot2)
library(sf)
#> Linking to GEOS 3.7.1, GDAL 2.4.2, PROJ 5.2.0
#> WARNING: different compile-time and runtime versions for GEOS found:
#> Linked against: 3.7.1-CAPI-1.11.1 27a5e771 compiled against: 3.7.0-CAPI-1.11.0
#> It is probably a good idea to reinstall sf, and maybe rgeos and rgdal too

df <- data.frame(
  longitude = -47,
  latitude = 45
)

p <- ggplot(df, aes(x = longitude, y = latitude)) +
  geom_point() +
  theme(
    plot.background = element_rect(fill = "black")
  )

tf <- tempfile(fileext = ".png")
ggsave(tf, p, width = 4, height = 4)

p

In the following example, I transform the data into an sf object and plot it using geom_sf() This cause the plot to have a certain aspect ratio to match the chosen projection.

df <- st_as_sf(df, coords = c("longitude", "latitude"), crs = 4326)

p <- ggplot(df) +
  geom_sf() +
  theme(
    plot.background = element_rect(fill = "black")
  )

tf <- tempfile(fileext = ".png")

However, setting the dimensions to 4 x 4 will cause paddings (white borders) to appear on the side of the plot. Hence, these white borders will be present when the graph is pasted into a PowerPoint presentation (for example).

ggsave(tf, p, width = 4, height = 4)

p

You can open tf and see the white padding around the black area. My question is about, how can I find the correct aspect ratio of the plot so I can provide appropriate dimensions to ggsave().

# Which dimensions to use to respect the aspect ratio of the map? 
# ggsave(tf, p, width = xxx, height = yyy) 

Created on 2019-11-28 by the reprex package (v0.3.0)

like image 371
Philippe Massicotte Avatar asked Nov 28 '19 13:11

Philippe Massicotte


1 Answers

Here is my solution to remove borders around ggplot2 graphs: https://www.pmassicotte.com/post/removing-borders-around-ggplot2-graphs/

like image 107
Philippe Massicotte Avatar answered Oct 18 '22 08:10

Philippe Massicotte