如何使用字符变量ggplot2 :: facet网格

时间:2019-09-02 19:53:27

标签: r ggplot2 facet

您好,在以下情况下,我想在某个函数中调用列上的facet_grid。问题是此列名存储在与该列本身具有相同名称的变量中。

library(ggplot2)
set.seed(1L)                                                      
DF = data.frame(x = rnorm(10), y = rnorm(10))                     
DF$grp = ifelse(DF$x >0, 'pos', 'neg')                            
DF2 = data.frame(x = rnorm(10), y = rnorm(10))
DF2$grp2 = ifelse(DF$x >0, 'pos', 'neg')                  
foo <- function(data, grp)                                        
{                                                                 
    p = ggplot(data) + aes_string(x = 'x', y = 'y') + geom_point()
    # this does not work because get(grp) is returning the grp variable and not the column
    p = p + facet_grid(rows = vars(get(grp)))                     
    return(p)                                                     
}                                                                 
foo(DF, 'grp')   # this fails                                                  
foo(DF2, 'grp2') # this works 

如何更改facet_grid行,这样我就不再担心这种极端情况了?

0 个答案:

没有答案