问题描述
在使用R脚本绘图时,有的图片背景需要根据数据大小调整(自适应图片大小的方法见:https://www.jianshu.com/p/aedb5cfd43dc),这时如果图片太大超出png的范围,会报错;Rstudio报错信息为:
Error in png(filename = "cluster_detail_heatmap.png", width = size, height = size, :
无法启动png()装置
In addition: Warning messages:
1: In png(filename = "cluster_detail_heatmap.png", width = size, height = size, :
无法分配bitmap
2: In png(filename = "cluster_detail_heatmap.png", width = size, height = size, :
opening device failed
终端执行R脚本,报错信息为:
Error in png(filename = "tmp.png", width = sz, height = sz, units = "cm", :
unable to start device 'png'
此外: Warning message:
In png(filename = "tmp.png", width = sz, height = sz, units = "cm", :
cairo error 'invalid value (typically too big) for the size of the input (surface, pattern, etc.)'
停止执行
问题解决
下面是查看在不同环境下所支持的png最大尺寸与res关系的R脚本:
# 需要输入两个参数
# $1 png size ;example: 1000 (png的大小)
# $2 res num; png的res数值(一般300)
args <- commandArgs(T)
sz=as.numeric(args[1])
resnum <- as.numeric(args[2])
pngsz=function(size,resnum){
png(filename = "tmp.png", width =size , height = size, units = "cm",res = resnum)
}
findmax=function(sz,resnum){
st="Blank"
while (st != "YES") {
tryCatch({
pngsz(sz,resnum)
st="YES"
dev.off()
print(sz)
},warning = function(w) {
},error = function(e) {
},finally = {
maxsize=sz
sz=sz-10 # 为输出的精度,-10表示真实值与输出值之差小于等于10
})
}
cat("maxsize=",maxsize,"\n","res=",resnum,"\n")
return (maxsize)
}
tryCatch({
st="NO"
pngsz(sz,resnum)
st="YES"
dev.off()
print(sz)
},warning = function(w) {
},error = function(e) {
},finally = {
maxsize=sz
})
#cat("st=",st,"\n")
if( st == "NO" ){
print("find max png ......")
maxsize=findmax(sz,resnum)
}else{
print("输入的图片数字需要增大")
print("The number of pictures entered needs to be increased")
}
if(st=="NO"){
tryCatch({
che="stat1"
png(filename = "tmp.png", width =10 , height = (maxsize*maxsize)/10, units = "cm",res = resnum)
dev.off()
che="stat2"
},warning = function(w) {
},error = function(e) {
},finally = {
})
if( che == "stat1" ){
cat("当前环境当res为",resnum,"时,png的width 和height 最大值为",maxsize,"\n")
cat(" In this device,when res=",resnum,";png limited width & height max=",maxsize,"\n")
}else{
cat("当前环境当res为",resnum,"时,png的width*height(面积)最大值为",maxsize*maxsize,"\n")
cat(" In this device,when res=",resnum,";png limited width * height; max=",maxsize*maxsize,"\n")
}
}
结论:
在Rstudio中,png的最大值为:width*height(面积);在终端中width 和height 各有相同的最大值,都不能超出这个值
终端下res与png大小的关系图
image.png
这种函数图像是幂函数,通过函数拟合计算出公式:y = 83450.31x^-1;y为大小,x为分辨率,至此绘图自适应大小的问题已经得到彻底解决