如何使用变量在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) )
在函数内部.但我希望能够使用函数的参数来挑选要用作颜色和组的列.IE.我想要这样的东西
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) )
我尝试过的一些事情:
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ) )
没有用.也没有
e <- environment()
ggplot( rates.by.groups, aes(x=name, y=rate, colour= columnName , group=columnName ), environment=e )
推荐答案
你可以使用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屋!