在 R 中保存高分辨率图像

我正在使用 R (R version 3.2.1)中的 ggplot 创建散点图。我想保存的图形作为一个在300分辨率的图像,以便在杂志上发表它。但是,我在 dev.off 中使用 ggsave 或 tiff ()的代码似乎不起作用,只能以96 DPI 格式保存。任何帮助都将不胜感激! !下面是我使用这两种方法的代码示例:

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()

输出为96DPI,宽度为1500像素,高度为1200像素。

211362 次浏览

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)