R ggsave保存缩略图大小(200 x 200),缩放图像

时间:2014-10-24 15:38:35

标签: r ggplot2

我试图用循环中的数据绘制一些简单的x,y线图。 代码将生成数百个这样的图,并且想法是将这些图保存在缩略图大小的图像(类似200 x 200像素,DPI无关紧要)中,并将其与数据一起嵌入Excel文件中。当我通过ggplot2进行绘制时,它看起来非常精细,但是当我想保存它时,我得到的裁剪图像只显示图像的一部分,或者是一个非常狭窄的图形,标签/文本的大小不匹配。如果我将比例设为2,那么它看起来是正确的,但不符合我的标准。

我的数据框看起来像这样。

Drug=c("A","A","A","A","A","A")
Con=c(10,100,1000,10,100,1000)
Treatment=c("Dox","Dox","Dox","Pac","Pac","Pac")
Value=c(-3.8,-4.5,-14.1,4,-4.6,3.5)
mat_tbl=data.frame(Drug,Con,Treatment,Value)

p=ggplot(data=mat_tbl,aes(x=Con,y=Value,colour=Treatment,group=Treatment))+geom_point(size =      4)+geom_line()+labs(title="Drug A",x="Concentration",y="Value") +    scale_y_continuous(limits=c(-25,125),breaks=seq(-25,125,by=25)) + theme_bw()
ggsave(filename = "curve_drug.png",plot=p,width=2,height=2,units="in",scale=1)

有关我需要处理哪些参数的任何建议?

1 个答案:

答案 0 :(得分:4)

请查看我为此编写的函数,作为ggsave的辅助函数:

plot.save <- function(plot, 
                       width = 800, 
                       height = 500, 
                       text.factor = 1, 
                       filename = paste0(
                                    format(
                                      Sys.time(), 
                                      format = '%Y%m%d-%H%M%S'), '-Rplot.png'
                                    )
                                  ) {

    dpi <- text.factor * 100
    width.calc <- width / dpi
    height.calc <- height / dpi

    ggsave(filename = filename,
                 dpi = dpi,
                 width = width.calc,
                 height = height.calc,
                 units = 'in',
                 plot = plot)
}

如您所见,DPI只不过是R中情节的文本因素。

考虑一下:

plot.save(some_ggplot, width = 400, height = 400, text.factor = 1)

pic1

这(将text.factor从1更改为0.5):

plot.save(some_ggplot, width = 400, height = 400, text.factor = 0.5)

pic2

两张图片都是400 x 400像素,就像我在函数中设置的一样。

也许有趣:plot.save的第一个参数是实际的ggplot。所以现在我做了以下可能(使用dplyr包),我经常使用它:

ggplot(...) %>%
  plot.save(200, 200) # here I've set width and height in pixels
相关问题