【发布时间】:2020-05-27 08:19:22
【问题描述】:
我必须以相同的格式绘制多个数据集,在多次复制粘贴代码后,我决定编写一个函数。 我理解 R 中的简单函数,并设法编写了以下内容:
testplot <- function(data, mapping){
output <- ggplot(data) +
geom_bar(mapping,
stat="identity",
position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))
这很好,但是,我的情节更复杂,需要“数据”参数单独进入每个组件:
output <- ggplot() +
geom_bar(df1, mapping,
stat="identity",
position='stack')+
geom_errorbar(df1, ...)+
geom+bar(df2, mapping,
...+
geom_errorbar(df2, ...)
但是当我编写函数并尝试将其运行为
output <- ggplot() +
geom_bar(data, mapping,
stat="identity",
position='stack')
}
p <- testplot(df, aes(x=xvar, y=yvar, fill=type))
它给了我一个错误:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class uneval Did you accidentally pass `aes()` to the `data` argument?
有办法解决吗?
编辑:当我尝试包含 2 个这样的数据框时:
testplot <- function(data, data2, mapping){
output <- ggplot() +
geom_bar(data=data, mapping=mapping,
stat="identity",
position='stack',
width = barwidth)+
geom_bar(data2=data2, mapping=mapping,
stat="identity",
position='stack',
width = barwidth)
}
p <- testplot(data=df, data2=df2, mapping=aes(x=norms_number, y=coeff.BLDRT, fill=type))
它说“忽略未知参数:data2”
【问题讨论】:
-
我很困惑。您实际运行的是哪个版本的
testplot?你在哪里定义了df?我在这里没有看到output与p有什么关系。 -
data2不是参数,只有data,因此您的第二行应该是geom_bar(data=data2, mapping = ...,请参阅我编辑的其余部分以获取完整说明。
标签: r function dataframe ggplot2