I'm creating a scatterplot using ggplot in R (R version 3.2.1). I want to save the graph as a tiff image in 300 DPI in order to publish it in a journal. However, my code using ggsave or tiff() with dev.off doesn't seem to work and only saves it in 96 DPI. Any help would be greatly appreciated!! Below is a sample of my code using both methods:
library(ggplot2) x <- 1:100 y <- 1:100 ddata <- data.frame(x,y) library(ggplot2) #using ggsave ggplot(aes(x, y), data = ddata) + geom_point() + geom_smooth(method=lm, fill = NA, fullrange=TRUE, color = "black") ggsave("test.tiff", units="in", width=5, height=4, dpi=300, compression = 'lzw') #using tiff() and dev.off tiff('test.tiff', units="in", width=5, height=4, res=300, compression = 'lzw') ggplot(aes(x, y), data = ddata) + geom_point() + geom_smooth(method=lm, fill = NA, fullrange=TRUE, color = "black") dev.off()
The output is a 96 DPI with a width of 1500 pixels and a height of 1200 pixels.
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300) # insert ggplot code dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) + geom_point() ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With