gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:29:06 27 4
gpt4 key购买 nike

我正在尝试用循环中的数据绘制一些简单的 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)

关于我需要处理哪些参数有什么建议吗?

最佳答案

请看一下我为此编写的函数,它是 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

关于R ggsave 保存缩略图大小(200 x 200),缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551359/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com