将参数传递给ggplot [英] passing parameters to ggplot

查看:120
本文介绍了将参数传递给ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想创建一个使用ggplot生成图形的函数。为了简单起见,典型图可以是

  ggplot(car,aes(x = speed,y = dist)) + geom_point()

我想创建的函数是类型

  f < - 函数(DS,x,y)ggplot(DS,aes(x = x,y = y))+ geom_point()

然而这不起作用,因为x和y不是字符串。在以前的SO问题中已经注意到这个问题(例如,这一个< a>),但在我看来,没有提供令人满意的答案。如何修改上面的函数使它能够处理任意的数据帧?解决方案一个解决方案是传递x和y作为数据帧DS中列的字符串名称。

  f < - 函数(DS,x,y){
ggplot(DS,aes_string(x = x,y = y))+ geom_point()
}

然后调用这个函数:

$ $ $ $ $ $ $ $ $ $ $ f $(汽车,速度,dist)

然而,您似乎并不想要这样?你能否提供一个例子说明为什么你需要不同的功能?是否因为你不想在同一个数据框中拥有参数?


would like to create a function that generates graphs using ggplot. For the sake of simplicity, the typical graph may be

ggplot(car, aes(x=speed, y=dist)) + geom_point() 

The function I would like to create is of the type

f <- function(DS, x, y) ggplot(DS, aes(x=x, y=y)) + geom_point()

This however won't work, since x and y are not strings. This problem has been noted in previous SO questions (e.g., this one), but without providing, in my view, a satisfactory answer. How would one modify the function above to make it work with arbitrary data frames?

解决方案

One solution would be to pass x and y as string names of columns in data frame DS.

f <- function(DS, x, y) {    
  ggplot(DS, aes_string(x = x, y = y)) + geom_point()  
}

And then call the function as:

f(cars, "speed", "dist")

However, it seems that you don't want that? Can you provide an example why you would need different functionality? Is it because you don't want to have the arguments in the same data frame?

这篇关于将参数传递给ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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