ggplot2,你如何使用函数内的访问数据框元素? [英] ggplot2, how do you use access dataframe elements from within the function?

查看:124
本文介绍了ggplot2,你如何使用函数内的访问数据框元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用ggplot2创建图表来标准化许多类似图的创建。考虑到你可以堆栈多个选项,使用+运算符使用theme(),stat _ *()或geom _ *(),你怎样把它包含在一个函数中?

我想创建一个函数来绘制数据框的部分,例如:

  library(ggplot2)
test <-function(fdata,fx){
p <-ggplot(fdata,aes(x = fx,y = mpg))+ geom_point()
print(p)};
test(mtcars,wt)

返回错误:

  eval(expr,envir,enclos)中的错误:object'fx'not found 

但将审美定义更改为本地作用域变量(例如x = fx至x = wt)可行,但不会使用该函数的第二个选项fx:

  library(ggplot2)
test< -function(fdata,fx){
p <-ggplot (fdata,aes(x = wt,y = mpg))+ geom_point()
print(p)};
test(mtcars,wt)

如何编写一个函数来创建一个绘图数据框中的不同变量?



例如我怎么写功能测试,以便我可以多次调用以获得类似的情节,如:

  test(mtcars,'wt ')#散点图wt x mpg 
test(mtcars,'disp')#散点图显示mpg
测试(mtcars,'hp')#散点图hp x mpg


解决方案

这里的技巧是使用 aes_string 而不是使用 aes 。前者允许您将字符串作为美学。这允许你传递一个包含审美字符串的变量,例如'wt'在绘制mtcars的情况下。您需要像这样修改您的代码:

  library(ggplot2)
test< - function(fdata,fx ){
p < - ggplot(fdata,aes_string(x = fx,y =mpg))+ geom_point()
print(p)
}
test(mtcars ,wt)


I'm trying to create plots in with ggplot2 to standardize the creation of many similar plots. Given you can stack numerous options, using theme(), stat_*(), or geom_*() with the + operator, how can you wrap this inside a function?

I'd like to create a function to plot sections of a data frame, for example :

library(ggplot2)
test<-function(fdata,fx){
  p<-ggplot(fdata,aes(x=fx,y=mpg))+geom_point()
  print(p)}; 
test(mtcars,wt)

returns an error of:

Error in eval(expr, envir, enclos) : object 'fx' not found

but changing the aesthetic definition to a locally scoped variable (e.g. x=fx to x=wt) works, but won't use the function's second option of 'fx':

library(ggplot2)
test<-function(fdata,fx){
  p<-ggplot(fdata,aes(x=wt,y=mpg))+geom_point()
  print(p)}; 
test(mtcars,wt)

How do I write a function to create a plot from different variables in a data frame?

E.g. how do I write function test so that I could call multiple times to get similar plots, like :

test(mtcars,'wt')  #scatter plot of wt x mpg
test(mtcars,'disp') #scatter plot of disp x mpg
test(mtcars,'hp')  #scatter plot of hp x mpg

解决方案

The trick here is to use aes_string instead of using aes. The former allows you to pass strings as aesthetics. This allows you to pass a variable containing the string of the aesthetic, e.g. 'wt' in case of plotting mtcars. You need to modify your code like this:

library(ggplot2)
test <- function(fdata, fx) {
  p <- ggplot(fdata, aes_string(x = fx, y = "mpg")) + geom_point()
  print(p)
}
test(mtcars, "wt")

这篇关于ggplot2,你如何使用函数内的访问数据框元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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