使用 ggplot2 进行元编程 [英] Metaprogramming with ggplot2

查看:10
本文介绍了使用 ggplot2 进行元编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to cut down on the amount of copying and pasting required to make a large number of charts with slightly differing functions / slices of the data.

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

Here is a simplified example of what I am trying to do:

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 中按它们分面.

I'd like to be able to have my function accept the variables to facet by as parameters. I was able to get this to work with respect to grouping by the columns in the data.table, but can't facet by them in ggplot.

推荐答案

你应该使用

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

在您的代码中.

这篇关于使用 ggplot2 进行元编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆