Skip to content

Instantly share code, notes, and snippets.

@benmarwick
Created December 19, 2020 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benmarwick/80d156cf86c15a9a37532207ee9fdc5c to your computer and use it in GitHub Desktop.
Save benmarwick/80d156cf86c15a9a37532207ee9fdc5c to your computer and use it in GitHub Desktop.
How to save a ggplot as a JPG file with specific dimensions and a high dpi
# How to save a ggplot as a JPG file with a
# specific dpi and dimensions, for example,
# because a publisher requires it
library(ggplot2)
p <-
ggplot(mtcars) +
aes(mpg,
disp) +
geom_point()
pngfile <- here::here("plot.png")
jpgfile <- here::here("plot.jpg")
dpi <- 1000
library(ragg)
# write PNG file with desired size and resolution
agg_png(pngfile,
width = 5,
height = 5,
units = "cm",
res = dpi,
scaling = 0.75)
p
invisible(dev.off())
# convert PNG to JPG
library(magick)
img_in <- image_read(pngfile)
png_2_jpg <- image_convert(img_in, "jpg")
image_write(png_2_jpg, jpgfile, density = dpi, quality = 100)
# may need to adjust base_size, label_size, aelement_text(size, and other
# text size values to make it look the right size in the JPG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment