R 通过使用 facet_wrap 和数据子集的函数调用传递 ggplot 的参数

R Passing arguments for ggplot through a function call with facet_wrap and data subsetting

我有一个纵向数据,我用 facet_wrap 和数据框的子集传递给 ggplot。我希望 'function'-alize 这个,但我 运行 遇到了麻烦。我看过与此类似的帖子,但没有看到 facet_wrap 和函数内部数据子集化的帖子。比如我以前用this post的资料做简单的图表。下面我展示了用于生成虚拟数据然后绘制图形的代码部分。那行得通。当我尝试使用我收到错误消息的函数调用时:

非常感谢您的帮助。谢谢!!

Error: Faceting variables must have at least one value

# Test

# Generate data
DF <- expand.grid(Time=(0:10), variable=as.factor(c("ux0", "ux1", "ux2")), model=as.factor(c("Model 1", "Model 2", "Model 3")))
DF$value <- DF$Time + rnorm(nrow(DF), 0, 20)

# load libraries
library(ggplot2)
library(scales)

# Define themes
My_Theme = theme_bw()+
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        aspect.ratio = 1,
        axis.title=element_text(size=7),
        axis.text.x=element_text(size=rel(0.6)),
        axis.text.y=element_text(size=rel(0.6)),
        strip.text = element_text(size = 6))

#Plot
my.plot  =  
  ggplot(subset(DF, variable %in% "ux1")) +
  geom_line(aes(x=Time, y=value)) +
  facet_wrap( ~ model, ncol=3) + 
  labs(x = "Time [s]", y = expression(paste("U"[X],","[1]))) +
  My_Theme
print(my.plot)

#Now try with function
makePlots <- function(data, subSetVar, subSetval, xVar, yVar, facetVar, 
                      xLabel, yLabel){

  # Common Theme to all plots

  My_Theme = theme_bw()+
    theme(panel.grid.major = element_blank(), 
          panel.grid.minor = element_blank(),
          aspect.ratio = 1,
          axis.title=element_text(size=7),
          axis.text.x=element_text(size=rel(0.6)),
          axis.text.y=element_text(size=rel(0.6)),
          strip.text = element_text(size = 6))

  my.plot  =  
    ggplot(subset(data, subSetVar %in% subSetval)) + 
    geom_line(aes(x=xVar, y=yVar)) + 
    facet_wrap(facetVar, ncol=3) + 
    labs(x = xLabel, y = yLabel) +
    My_Theme


  # Output to Plots window in RStudio
  print(my.plot)

}

my.plot <- makePlots(DF, "variable", "ux1", "Time", "value", "model",
                     "Time [s]", expression(paste("U"[X],","[1])))

'''

为了将字符串作为变量传递给 ggplot,您需要在 my.plot 部分进行一些更改,然后再将其包装到函数中。

对于数据集的子集,您需要使用 [[ ]] 传递列的名称才能使其工作。对于xy的定义,可以使用aes_string(https://ggplot2.tidyverse.org/reference/aes_.html). Finally, for facetting, pass your character vector as a formula (as explained in this post: Passing string variable facet_wrap() in ggplot using R).

my.plot  =  
    ggplot(subset(data, data[[subSetVar]] %in% subSetval)) + 
    geom_line(aes_string(x=xVar, y=yVar)) +
    facet_wrap(as.formula(paste("~", facetVar)), ncol=3) + 
    labs(x = xLabel, y = yLabel) +
    My_Theme

然后,它应该可以工作并为您提供相同的图表:

my.plot <- makePlots(DF, "variable", "ux1", "Time", "value", "model",
                     "Time [s]", expression(paste("U"[X],","[1])))

它是否回答了您的问题?