如何使用变量在ggplot中指定列名称 [英] How to use a variable to specify column name in ggplot
问题描述
我有一个ggplot命令
I have a ggplot command
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
函数。但我希望能够使用函数的参数来挑选出要用作颜色和组的列。即我希望像这样
inside a function. But I would like to be able to use a parameter of the function to pick out the column to use as colour and group. I.e. I would like something like this
f <- function( column ) {
...
ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) )
}
因此ggplot中使用的列由参数决定。例如。对于f(majr),我们得到的效果是:
So that the column used in the ggplot is determined by the parameter. E.g. for f("majr") we get the effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
但是对于f(gender)我们得到的效果是:
but for f("gender") we get the effect of
ggplot( rates.by.groups, aes(x=name, y=rate, colour=gender, group=gender) )
我试过的一些东西:
Some things I tried:
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ) )
不起作用。
did not work. Nor did
e <- environment()
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ), environment=e )
推荐答案
您可以使用 aes_string
:
You can use aes_string
:
f <- function( column ) {
...
ggplot( rates.by.groups, aes_string(x="name", y="rate", colour= column,
group=column ) )
}
只要您将该列传递给该函数字符串( f(majr)
)而不是 f(majr)
)。另请注意,我们将其他列name
和rate
更改为字符串。
as long as you pass the column to the function as a string (f("majr")
rather than f(majr)
). Also note that we changed the other columns, "name"
and "rate"
, to be strings.
如果出于某种原因,您宁愿不使用 aes_string
,您可以将其更改为(更麻烦):
If for whatever reason you'd rather not use aes_string
, you could change it to (the somewhat more cumbersome):
ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
group=get(column) ) )
这篇关于如何使用变量在ggplot中指定列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!