在R中保存高分辨率图像

时间:2016-08-11 23:16:32

标签: r ggplot2

我在R(R版本3.2.1)中使用ggplot创建散点图。我想将图表保存为300 DPI中的tiff图像,以便将其发布到日记中。但是,我的代码使用ggsave或tiff()与dev.off似乎不起作用,只能将其保存在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()

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

2 个答案:

答案 0 :(得分:42)

您可以执行以下操作。在第一行代码后添加ggplot代码,以dev.off()结束。

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300指定您需要一个分辨率为300 dpi的数字。名为&#39; test.tiff&#39;的图形文件保存在your working directory

根据所需的输出更改上述代码中的widthheight

请注意,这也适用于其他R图,包括plotimagepheatmap

其他文件格式

除了TIFF之外,您还可以轻松使用other image file formats,包括JPEG,BMP和PNG。其中一些格式需要较少的内存来保存。

答案 1 :(得分:9)

更简单的方法是

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
相关问题