我有一个ggplot命令
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
在函数内部。 不过,我想能够使用该函数的参数挑选出列的颜色和组使用。 即我想是这样的
f <- function( column ) {
...
ggplot( rates.by.groups, aes(x=name, y=rate, colour= ??? , group=??? ) )
}
因此,在ggplot使用的列是由参数决定。 例如,对于F(“majr”),我们得到的效果
ggplot( rates.by.groups, aes(x=name, y=rate, colour=majr, group=majr) )
但对于f(“性别”),我们得到的效果
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"
,是字符串。
如果出于某种原因,你宁愿不使用aes_string
,你可以将其更改为(有点更麻烦):
ggplot( rates.by.groups, aes(x=name, y=rate, colour= get(column),
group=get(column) ) )
从发行说明的ggplot2 V3.0.0
:
AES()现在支持quasiquotation,这样就可以使用!!!!!和:=。 这将替换aes_()和aes_string(),这是现在的软弃用(但仍将在很长一段时间)。
现在的惯用方式是变量包含使用转换为符号的字符串ensym
,并且使用解除引用它!!
模拟OP的数据,我们可以这样做:
library(tidyverse)
rates.by.groups <- data.frame(
name = LETTERS[1:3],
rate = 1:3,
mjr = LETTERS[c(4,4,5)],
gender = c("M","F","F")
)
f <- function(column) {
ggplot(rates.by.groups,
aes(x = name,
y = rate,
fill = !!ensym(column),
group = !!ensym(column))) +
geom_fill()
}
f("gender")
f("mjr")
如果我们宁愿饲料原料名称的功能,我们可以这样做:
f2 <- function(column) {
column <- enquo(column)
ggplot(rates.by.groups,
aes(x = name,
y = rate,
fill = !!column,
group = !!column)) +
geom_fill()
}
f2(gender)
f2(mjr)
另一种选择( ggplot2 > 3.0.0
)是使用整齐评价代词.data
从切片选择变量/列rates.by.groups
数据帧。
library(ggplot2)
theme_set(theme_classic(base_size = 14))
# created by @Moody_Mudskipper
rates.by.groups <- data.frame(
name = LETTERS[1:3],
rate = 1:3,
mjr = LETTERS[c(4, 4, 5)],
gender = c("M", "F", "F")
)
f1 <- function(df, column) {
gg <- ggplot(df,
aes(x = name,
y = rate,
fill = .data[[column]],
group = .data[[column]])) +
geom_col() +
labs(fill = column)
return(gg)
}
plot_list <- lapply(list("gender", "mjr"), function(x){ f1(rates.by.groups, x) })
plot_list
#> [[1]]
#>
#> [[2]]
# combine all plots
library(egg)
ggarrange(plots = plot_list,
nrow = 2,
labels = c('A)', 'B)'))
由创建于2019年4月4日reprex包 (v0.2.1.9000)