You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在函数内调用eulerr包绘图生成空PDF的问题求助

eulerr包在R自定义函数内生成空PDF的问题解决

我使用R的eulerr包编写了一个自定义函数,用于生成欧拉图并保存为PDF,但执行函数后生成的PDF为空;相同逻辑的代码放在函数外执行却能正常生成预期的欧拉图。

函数内的问题代码

library(eulerr)

test <- function(listA,listB,file,labels,title){
  euler <- euler(list("A"=listA, "B"=listB))
  
  #plot euler object and save to file
  pdf(paste0("euler/",file,".pdf"))
  plot(euler,
       "quantities"=TRUE,
       "labels"=labels,
       "main"=title)
  dev.off()
}

test(c("A","B","C","D"),
     c("C","D","E","F","G"),
     "test",
     c("list A","list B"),
     "TITLE")

函数外正常运行的代码

library(eulerr)

listA <- c("A","B","C","D")
listB <- c("C","D","E","F","G")
labels <- c("list A","list B")
file <- "test"
title <- "TITLE"

euler <- euler(list("A"=listA, "B"=listB))
  
#plot euler object and save to file
pdf(paste0("euler/",file,".pdf"))
plot(euler,
     "quantities"=TRUE,
     "labels"=labels,
     "main"=title)
dev.off()

问题原因

eulerr包的plot()函数返回的是ggplot类绘图对象,在R的函数内部(非交互环境),这类对象不会自动渲染到绘图设备;而在交互环境(函数外直接运行代码)中,R会自动打印绘图对象,所以能正常生成PDF内容。

解决方法

有两种可行的修正方式:

方式1:用print()显式触发绘图渲染

在函数内将plot()的结果用print()包裹,强制将绘图内容写入PDF设备:

library(eulerr)

test <- function(listA,listB,file,labels,title){
  euler <- euler(list("A"=listA, "B"=listB))
  
  pdf(paste0("euler/",file,".pdf"))
  # 用print包裹plot语句,触发渲染
  print(plot(euler,
             quantities=TRUE,
             labels=labels,
             main=title))
  dev.off()
}

test(c("A","B","C","D"),
     c("C","D","E","F","G"),
     "test",
     c("list A","list B"),
     "TITLE")

方式2:用ggsave()直接保存绘图对象

利用ggplot2的ggsave()函数直接保存plot()生成的绘图对象,这种方式更简洁且避免设备管理的问题:

library(eulerr)
library(ggplot2)

test <- function(listA,listB,file,labels,title){
  euler <- euler(list("A"=listA, "B"=listB))
  
  # 先生成绘图对象
  p <- plot(euler,
            quantities=TRUE,
            labels=labels,
            main=title)
  # 用ggsave保存
  ggsave(paste0("euler/",file,".pdf"), plot = p)
}

test(c("A","B","C","D"),
     c("C","D","E","F","G"),
     "test",
     c("list A","list B"),
     "TITLE")

内容的提问来源于stack exchange,提问作者justinian482

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 06:05:43