【问题标题】:Error creating facets in ggplot2-based plotting function在基于 ggplot2 的绘图函数中创建构面时出错
【发布时间】:2015-12-09 19:16:29
【问题描述】:

所以我正在尝试为现有的 R 包开发基于ggplot2的绘图功能。用户应该能够指定一个数据框(datfile),一个垂直线放置在图中的值(alpha),以及一个用于通过分面创建子图的分组变量(group)。

以下是一些示例数据:

#Some hypothetical data
Computed=c(0.03, 0.25, 0.74, 0.02, 0.0023, 0.43, 0.56, 0.32, 0.005, 0.0032, 0.06)
Reported.P.Value=c(0.25, 0.24, 0.74, 0.01, 0.001, 0.40, 0.56, 0.32, 0.003, 0.0032, 0.02)
Journal=c("a", "b","a", "b","a", "b","a", "b","a", "b","a")

dat=data.frame(Computed, Reported.P.Value, Journal)

函数如下所示:

plot1 <- function(datfile, alpha, group){

p <- ggplot(datfile, aes(y = Computed,x = Reported.P.Value))   

p + geom_point(size=2.5)+
  geom_vline(xintercept=alpha, color="grey60",linetype="dashed")+
  geom_abline(intercept=0, slope=1, color="grey60")+
  annotate("text", x= 0.5, y = .10, label="overestimated")+
  annotate("text", x= 0.5, y = .90, label="underestimated")+
  scale_x_continuous(name="Reported p-values", breaks=c(0.00, 0.05, 0.10, 0.25, 0.50, 0.75, 1.0))+
  scale_y_continuous(name="Computed p-values", breaks=c(0.00, 0.05, 0.10, 0.25, 0.50, 0.75, 1.0))+
  facet_grid(group ~ .)
 }

如果我忽略该函数,只自己执行绘图代码(从数据框中替换适当的向量),一切正常:

但是如果尝试运行绘图函数本身的函数...:

plot1(dat, 0.05, Journal)

我收到以下错误消息: Error in layout_base(data, rows, drop = drop) : At least one layer must contain all variables used for faceting

我的错误似乎与here 讨论的问题有关,接受答案的作者写道:

facet_grid 是更特殊的必需名称,甚至不是其功能。

这是否意味着我无法将数据框中的变量传递给函数中的 faceting 选项?我的编程背景并不出色,如果我的函数的用户无法指定分面变量,那将是一个真正的遗憾。非常感谢任何帮助!

【问题讨论】:

    标签: r function plot ggplot2


    【解决方案1】:

    对原始代码的两个更改:使用paste 将构面语句传递给facet_grid 以构造适当的字符串(根据@aosmith 的评论,不需要公式包装器),然后将构面变量传递给函数一个字符串。

    plot1 <- function(datfile, alpha, group){
    
      p <- ggplot(datfile, aes(y = Computed,x = Reported.P.Value))   
    
      p + geom_point(size=2.5)+
        geom_vline(xintercept=alpha, color="grey60",linetype="dashed")+
        geom_abline(intercept=0, slope=1, color="grey60")+
        annotate("text", x= 0.5, y = .10, label="overestimated")+
        annotate("text", x= 0.5, y = .90, label="underestimated")+
        scale_x_continuous(name="Reported p-values", breaks=c(0.00, 0.05, 0.10, 0.25, 0.50, 0.75, 1.0))+
        scale_y_continuous(name="Computed p-values", breaks=c(0.00, 0.05, 0.10, 0.25, 0.50, 0.75, 1.0))+
        facet_grid(paste(group, "~ ."))
    }
    
    plot1(dat, 0.5, "Journal")
    

    【讨论】:

    • 你能解释一下这个问题吗?
    • @Soheil, facet_grid 需要一个公式,因此如果我们希望函数灵活,我们需要以编程方式构建公式。要将正确的列传递给公式,我们需要一个字符串,因为Journal 在默认环境中不是独立对象。因此,我们将它作为一个字符串传递给公式,然后 ggplot 知道在数据框中查找输入函数的列。我不确定这是否是最优雅的方式,但它确实有效。
    • facet_grid 函数可以接受除公式之外的字符串。字符串必须看起来像,例如,“Journal ~ .”,所以这里唯一真正的简化是不需要 as.formula 包装器。
    • 我已经相应地更新了我的代码。感谢您的评论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多