93

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.

3
  • You might need to set height and width (and units) Aug 11, 2016 at 23:45
  • 1
    The code works with simulated data! The problem should be at your plot, so a reproducible example is needed
    – Robert
    Aug 11, 2016 at 23:50
  • 1
    Agreed. Works fine for me -- what are the pixel dimensions of your output, and what does ggplot say when you call ggsave()? Aug 12, 2016 at 0:19

2 Answers 2

Reset to default

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

111

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.

26

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.