【问题标题】:Function to use all factor levels in a plot when none are specified未指定时使用绘图中所有因子水平的函数
【发布时间】:2016-01-08 19:33:06
【问题描述】:

这个问题与我今天提出的另一个问题相似,但似乎不同,值得单独提出一个问题。如果这种想法是错误的,请告诉我。我写了一个函数,它有一个因子水平的输入。

我想做的是修改我的函数,以便在未指定因子级别时使用所有因子级别。这是我的意思的一个例子:

plotfunc <- function(Data, x, y,Species.Name){
  DataS <- Data %>% filter(Species %in% Species.Name)
  print(
    ggplot(DataS, aes_q(x = substitute(x), y = substitute(y))) + 
      geom_point() +
      facet_wrap(~Species)
   )
}

以 1 个因子级别调用函数:

plotfunc(Data=iris, x=Petal.Width, y=Petal.Length,Species.Name=c('versicolor'))

或者甚至用两个来称呼它:

plotfunc(Data=iris, x=Petal.Width, y=Petal.Length,Species.Name=c('versicolor','virginica'))

所需的行为是这样的,它利用了所有因素水平:

plotfunc(Data=iris, x=Petal.Width, y=Petal.Length)

提前致谢。

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    此函数非常特定于iris 数据,但您可以使用以下函数:

    plotfunc <- function(Data, x, y,Species.Name=NULL){
      if(is.null(Species.Name)) Species.Name = unique(Data$Species)
      DataS <- Data %>% filter(Species %in% Species.Name)
      print(
        ggplot(DataS, aes_q(x = substitute(x), y = substitute(y))) + 
          geom_point() +
          facet_wrap(~Species)
      )
    }
    

    关键是将变量设置为NULL,然后检查开头是否为NULL

    更新:

    对于更通用的功能,您只需要找到一种方法来删除特定于iris 数据的那些东西。在这里,我添加了一个名为 group.col 的变量,它表示要使用哪一列进行分组:

    plotfunc <- function(Data, x, y, group.col, groups=NULL){
      if(is.null(groups)) groups = unique(Data[,group.col])
      DataS <- Data[Data[,group.col] %in% groups,]
      print(
        ggplot(DataS, aes_q(x = substitute(x), y = substitute(y))) + 
          geom_point() +
          facet_wrap(~Species)
      )
    }
    plotfunc(Data=iris, x=Petal.Width, y=Petal.Length, group.col=5)
    plotfunc(Data=iris, x=Petal.Width, y=Petal.Length, group.col=5, groups=c('versicolor'))
    

    【讨论】:

    • 谢谢。知道如何使函数更通用吗?这就是您如何在函数调用中指定因子列名称,以便更广泛地适用。
    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多