R-将参数传递给函数中的ggplot [英] R- pass argument to ggplot in function
问题描述
我有一个问题,如果我想使用 1-x
x轴,如何将参数传递给ggplot.该功能用于在我的数据框中指定列名.
I have a question about how to pass an argument to ggplot if I want to have a 1-x
x-axis. The function is being used to specify column name in my data frame.
假设我的数据框看起来像
Let's say my data frame looks like
x1 x2 x3 x4
0.1 0.2 0.3 0.4
0.3 0.5 0.7 0.9
0.4 0.6 0.8 0.2
我有一个功能
myfunction<- function(x, y, convert = False){
if (flip) {
ggplot(data = mydata, aes(x=1-get(x), y=get(y))) + geom_line() +
xlab(x) + ylab(y)
} else {
ggplot(data = mydata, aes(x=get(x), y=get(y))) + geom_line() +
xlab(x) + ylab(y)
}
}
当convert = False时它可以工作,但是如果我想绘制 myfunction(x1,x2,convert = TRUE)
,我的x-lab仍然是"x1"
,而不是"1-x1"
.我尝试编码 xlab(1-get(x))
,但是它不起作用.任何人都有关于如何将x-label打印为"1-x1"
的想法,其中x1是数据框中的列名?
It works when convert = False, but if I want to plot myfunction(x1, x2, convert = TRUE)
, my x-lab is still "x1"
, not "1-x1"
. I have tried to code xlab(1-get(x))
but it doesn't work. Anyone have an idea about how to print x-label as "1-x1"
, where x1 is a column name in a data frame?
推荐答案
基于函数参数,看来 convert
是 flip
.无需使用 get
修改'x'参数,我们可以在将参数转换为quosures后使用 mutate
进行此操作.
Based on the function arguments, it seems like convert
is flip
. Instead of using get
to modify the 'x' argument, we can do this with mutate
after converting the arguments to quosures
myfunction<- function(mydata, x, y, convert = FALSE){
x <- enquo(x)
y <- enquo(y)
xnew <- quo_name(x)
if (convert) {
mydata %>%
mutate(!! (xnew) := 1- !!(x)) %>%
ggplot(., aes_string(xnew, quo_name(y))) +
geom_line() +
xlab(paste0("1 - ", xnew))
} else {
ggplot(mydata, aes_string(xnew, quo_name(y))) +
geom_line()
}
}
myfunction(df1, x1, x2, convert = TRUE)
-输出
myfunction(df1, x1, x2, convert = FALSE)
-输出
df1 <- structure(list(x1 = c(0.1, 0.3, 0.4), x2 = c(0.2, 0.5, 0.6),
x3 = c(0.3, 0.7, 0.8), x4 = c(0.4, 0.9, 0.2)), .Names = c("x1",
"x2", "x3", "x4"), class = "data.frame", row.names = c(NA, -3L
))
这篇关于R-将参数传递给函数中的ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!