r - 在基于 ggplot2 的绘图函数中创建构面时出错

标签 r function plot ggplot2

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

以下是一些示例数据:

#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 ~ .)
 }

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

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

plot1(dat, 0.05, Journal)

我收到此错误消息: layout_base(data, rows, drop = drop) 中的错误: 至少一层必须包含用于分面的所有变量

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

facet_grid is even more particular required names, not even functions thereof.

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

最佳答案

对原始代码的两处更改:使用 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")

关于r - 在基于 ggplot2 的绘图函数中创建构面时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553761/

相关文章:

MATLAB 同时在单独的子图中绘制移动数据点

r - 如何在 geom_tile 中设置单独的列宽(在 ggplot2 中)

r - 我可以在R的ggplot2中使用晶格中的带状疱疹吗

c - 无需等待即可获取用户输入 - C 语言..!

javascript - 为什么我的 JavaScript 代码没有调用我的函数?

c# - ILSurface 绘图参数

ggplot2图例不出现的原因

r - 如何与同一组中序列中相邻的值进行比较

function - 如何在Rust中将通用函数指针存储为 `any`?

matlab - Matlab 中的精英主义?