gpt4 book ai didi

r - 使用 ggplot2 进行元编程

转载 作者:行者123 更新时间:2023-12-04 22:32:06 25 4
gpt4 key购买 nike

我一直在尝试减少制作大量功能/数据切片略有不同的图表所需的复制和粘贴量。

这是我正在尝试做的一个简化示例:

test <- data.table(a=c("x","y"), b=seq(1,3), c=rnorm(18))

fixedSlices <- function(input, rowfacet, colfacet, metric){
calc <- substitute(metric)
bygroup<-c(rowfacet,colfacet)
aggregates <- input[,eval(calc),by=bygroup]

ggplot(aggregates) + geom_point(stat="identity") + aes(x="", y=V1) + facet_grid(a ~ b)
}
fixedSlices(test, "a", "b", mean(c)) #works

dynamicSlices <- function(input, rowfacet, colfacet, metric){
calc <- substitute(metric)
bygroup<-c(rowfacet,colfacet)
aggregates <- input[,eval(calc),by=bygroup]

ggplot(aggregates) + geom_point(stat="identity") + aes(x="", y=V1) + facet_grid(eval(rowfacet) ~ eval(colfacet))
}
dynamicSlices(test, "a", "b", mean(c))
#Error in layout_base(data, rows, drop = drop) : At least one layer must contain all variables used for facetting

我希望能够让我的函数接受要分面的变量作为参数。我能够通过 data.table 中的列进行分组,但不能在 ggplot 中对它们进行分组。

最佳答案

你应该使用

... + facet_grid(as.formula(sprintf("%s ~ %s", rowfacet, colfacet))

在你的代码中。

关于r - 使用 ggplot2 进行元编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com