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

查看:126
本文介绍了使用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

我想能够让我的函数接受变量作为参数facet。

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天全站免登陆