ggplot在函数中不起作用,以字符串形式传递变量名称 [英] ggplot does not work in function, passing in variable names as strings

查看:509
本文介绍了ggplot在函数中不起作用,以字符串形式传递变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单的功能,但它的ggplot命令不起作用。从命令行给出的命令可以正常工作:

I have following simple function but its ggplot command does not work. The command works all right when given from command line:

> testfn <- function(gdf, first, second){          
   library(ggplot2) 
   print(ggplot(gdf, aes(first, second)) + geom_point()) 
}                                                                                              
>
> testfn(mydataf, vnum1, vnum2)   
    Error in eval(expr, envir, enclos) : object 'second' not found
> 
> ggplot(mydataf, aes(vnum1, vnum2)) + geom_point()

>  (plots graph without any error)

我尝试使用 aes_string 而不是 aes ;并使用 x = first,y = second 。事情有所改善,并且绘制了一个点! X轴和Y轴显示与该点相关的数字作为标签。只有第一行正在绘制。哪里有问题。感谢您的帮助。

I tried to use aes_string instead of aes; and also using x=first, y=second. Things improve and one point is plotted! X and Y axes show numbers related to that point as the label. Only the first row is being plotted. Where is the problem. Thanks for your help.

推荐答案

(根据我最初的建议和您的确认)

(As per my initial suggestion and your confirmation)

这是关于如何将变量名的字符串参数传递到您的fn。

It was about how you were trying to pass string arguments of variable names into your fn.


  • 在命令行上, ggplot(gdf,aes(first,second))可以正常工作

  • 但在函数内部,第一,第二个是字符串变量。因此,您现在需要在函数testfn中 aes_string(first,second),因为您现在通过字符串变量first,second间接地传递变量名称。 / li>
  • 也是因为变量名称第一个,第二个是字符串,是的,您在调用fn时需要引用它们。 (我不确定什么语言机制ggplot的 aes()用来不需要字符串,但是不管用什么。)

  • 另请参阅R中的 quote()命令
  • on the command-line, ggplot(gdf, aes(first, second)) would work fine
  • but inside your function, you're also passing in first,second as string variables. So yes you would now need aes_string(first,second) inside your function testfn, since you're now passing variable names indirectly, through the string-variables first,second.
  • also since the variable-names first,second are strings, yes you do need to quote them when you call the fn. (I'm not sure what language mechanism ggplot's aes() uses to not need strings, but whatever. Use quotes.)
  • see also the quote() command in R

这篇关于ggplot在函数中不起作用,以字符串形式传递变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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