How to save a ggplot as a JPG file with specific dimensions and a high dpi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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