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

Swa*_*dar 5 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)
Run Code Online (Sandbox Code Playgroud)

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

MS *_*nds 7

请看一下我编写的用于执行此操作的函数,作为以下的辅助函数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)
}
Run Code Online (Sandbox Code Playgroud)

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

考虑一下:

plot.save(some_ggplot, width = 400, height = 400, text.factor = 1)
Run Code Online (Sandbox Code Playgroud)

图片1

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

plot.save(some_ggplot, width = 400, height = 400, text.factor = 0.5)
Run Code Online (Sandbox Code Playgroud)

图片2

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


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

ggplot(...) %>%
  plot.save(200, 200) # here I've set width and height in pixels
Run Code Online (Sandbox Code Playgroud)