通过R中的ggplot在函数中传递带有可选构面的变量列 [英] Pass variable columns with optional facets in a function via ggplot in R

查看:76
本文介绍了通过R中的ggplot在函数中传递带有可选构面的变量列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何使用一个函数创建多个ggplots,以避免繁琐的复制和粘贴.当我想在同一data.frame中使用不同的列时,我不想在函数中更改参数名称.解决此问题的方法可能完全不同,但是我包括了两次尝试,它们几乎都奏效了,但仍达不到我想要的效果. 谢谢!

I am trying to figure out how to create multiple ggplots with one function, to avoid tedious copying and pasting. I do not want to have to change argument names in the function when I want to use different columns in the same data.frame. There may be completely different approach to this problem, but I am including two attempts that almost worked but still fall short of what I want. Thanks!

修改 我还希望该函数根据参数添加构面,例如groupBy ="brand".我认为aes_string与 https://stat.ethz.ch一起/pipermail/r-help/2009-October/213946.html 可能会让我到达那里.我将构面请求包括在我的问题中,因为仅aes_string不能实现将其作为plot函数一部分的目标.我将品牌添加到数据集中,只是为了分享今天通过在线搜索找不到的内容.

Edit I would also like the function to add a facet depending on on argument, such as groupBy="brand", for example. I think aes_string along side of https://stat.ethz.ch/pipermail/r-help/2009-October/213946.html may get me there. I included my facet request as part of my question, because aes_string alone falls short of my goal of being able to facet as part of the plot function. I added brand to the dataset, just to share what I could not find by searching online today.

library(ggplot2)

### sample data ###
n=25
dataTest = data.frame(
  xVar=sample(1:3, n, replace=TRUE), 
  yVar = rnorm(n, 5, 2), 
  zVar=rnorm(n, 5, .5),
  brand=letters[1:5])

### a first attempt ###
  ### works, but forces me to create a new function whenever column names need to change
  my_plot =function(data) {ggplot(data=data, aes(x=xVar, y=yVar))+geom_bar(stat="identity")}
  do.call("my_plot", list(data=dataTest))
  ### wish for something like this... but this does not work
  my_plot = function(data) {ggplot(data=data, aes(x=x, y=y))+geom_bar(stat="identity")}
  do.call("my_plot", list(data=dataTest, x=xVar, y=yVar))
  do.call("my_plot", list(data=dataTest, x=xVar, y=zVar))

### a second attempt, does not work ###
my.plot = function(x, y, data)
{
  arguments <- as.list(match.call())
  data = eval(arguments$data, envir=data)
  x = eval(arguments$x, envir=data)
  y = eval(arguments$y, envir=data)
  p=ggplot(data=data, aes(x, y))+geom_bar(stat="identity")
  return(p)
}
my.plot(x=xVar, y=yVar, data=dataTest)

推荐答案

使用aes_string将使您可以将字符串传递到ggplot2函数中,从而可以通过编程方式更轻松地对其进行更改:

Using aes_string will allow you to pass character strings into your ggplot2 function, allowing you to programmatically change it more easily:

my.plot = function(x, y, data)
{
p=ggplot(data, aes_string(x=x, y=y))+geom_bar(stat="identity")
print(p)
}

my.plot(x="xVar", y="yVar", data=dataTest)

my.plot(x="xVar", y="zVar", data=dataTest)

这篇关于通过R中的ggplot在函数中传递带有可选构面的变量列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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