【问题标题】:Cannot save plots as pdf when ggplot function is called inside a function在函数内部调用 ggplot 函数时无法将绘图保存为 pdf
【发布时间】:2015-06-10 22:53:14
【问题描述】:

我将使用 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

有人可以帮忙吗?

【问题讨论】:

标签: r pdf ggplot2 printing boxplot


【解决方案1】:

您的示例不是很清楚,因为您进行了调用,但没有显示变量的值,因此很难弄清楚您要做什么(例如,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())

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 2021-01-22
    相关资源
    最近更新 更多