R- 在函数中将参数传递给 ggplot [英] R- pass argument to ggplot in function

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

问题描述

如果我想要一个 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屋!

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