在函数内部调用 ggplot 函数时无法将绘图保存为 pdf

Cannot save plots as pdf when ggplot function is called inside a function

我将使用 ggplot 从 4 列矩阵 pl1 绘制一个箱线图,每个箱子上都有点。绘图指令是这样的:

p1 <- ggplot(pl1, aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05))+ 
  geom_boxplot(aes(fill=method), outlier.shape= NA)+ 
  theme(text = element_text(size=20), aspect.ratio=1)+
  xlab("Number of edges")+
  ylab(y_label)+
  scale_fill_manual(values=color_box)+
 geom_point(aes(x=factor(Edge_n), y=get(make.names(true_des)), ymax=max(get(make.names(true_des)))*1.05, color=method), 
              position = position_dodge(width=0.75))+
  scale_color_manual(values=color_pnt)

然后,我使用 print(p1) 将其打印在打开的 pdf 上。但是,这对我不起作用,我收到以下错误:

Error in make.names(true_des) : object 'true_des' not found

有人可以帮忙吗?

你的例子不是很清楚,因为你打了电话,但没有显示变量的值,所以很难弄清楚你想做什么(例如,是 method 数据框中列的名称 pl1,或者它是一个变量(如果它是一个变量,它的类型是什么?字符串?名称?)。

尽管如此,这里有一个示例可以帮助您按照自己的意愿行事:

尝试这样的事情:

pl1 <- data.frame(Edge_n = sample(5, 20, TRUE), foo = rnorm(20), bar = rnorm(20))

y_label <- 'foo'

ax <- do.call(aes, list(
    x=quote(factor(Edge_n)), 
    y=as.name(y_label), 
    ymax = substitute(max(y)*1.05, list(y=as.name(y_label)))))

p1 <- ggplot(pl1) + geom_boxplot(ax)
print(p1)

这应该让您开始弄清楚您要尝试做的其他事情。

或者(对您的问题的不同解释)是您可能 运行 遇到 aes 评估其参数的环境问题。有关详细信息,请参阅 https://github.com/hadley/ggplot2/issues/743。如果这是问题所在,那么答案可能会将 environment 参数的默认值覆盖为 aes,例如:aes(x=factor(Edge_n), y=get(make.names(y_label)), ymax=max(get(make.names(y_label)))*1.05, environment=environment())