ggplot无法使用facet_wrap和group asthetic绘制流畅的游戏

乔治

我正在尝试使用ggplot绘制具有多组美学效果的多面板和多线图facet_wrap但是,geom_smooth当一组数据点太少时,构面图中的所有线都失败。

plot1 <- ggplot(data=df1, 
                aes(x=Year, y=Mean, group=Group2, linetype=Group2, shape=Group2)) +  
  geom_errorbar(aes(ymin=Mean-SE, ymax=Mean+SE), width=0.2) +  
  geom_smooth(method = "gam", se=F, formula = y ~ s(x, k=3), size = 1, colour="black") + 
  geom_point(position=pd, size=2, fill="white") +  
  scale_x_continuous(limits=c(min(df1$Year-0.1), max(df1$Year+0.1)), 
                     breaks=seq(min(df1$Year),max(df1$Year),5)) +  
  facet_wrap(~Group1, scales = "free", ncol=2) +  
  theme_bw() + 
  theme(axis.text.x = element_text(),
        axis.title.x = element_blank(), 
        strip.background = element_blank(), 
        axis.line.x = element_line(colour="black"),
        axis.line.y = element_line(colour="black"), 
        panel.grid.minor = element_blank(), 
        panel.grid.major = element_blank(),
        panel.border = element_blank(), 
        panel.background = element_blank(),
        legend.position="top",
        legend.title = element_blank())
plot(plot1)

产生以下图。这仅是摘要数据,以使其更容易。就像错误使ggplot停止计算该特定平面上的序列平滑一样。

数据

Year    Group1      Group2      Mean        SE
2011    Factor A    Factor C    30.62089116 3.672624771
2011    Factor A    Factor D    54.99066324 2.822405771
2011    Factor B    Factor C    30.48859003 3.748388489
2011    Factor B    Factor D    45.70410611 4.284244405
2017    Factor A    Factor C    33.68256601 4.030964172
2017    Factor A    Factor D    53.43496462 4.687042033
2017    Factor B    Factor C    23.08799875 5.17753488
2001    Factor A    Factor C    23.79166667 2.837795432
2001    Factor A    Factor D    23.75925926 3.688185081
2001    Factor B    Factor C    29.05555556 4.08597798
2001    Factor B    Factor D    28.13333333 7.877429079
2008    Factor A    Factor C    23.3        2.383624691
2008    Factor A    Factor D    28.83333333 2.750959429
2008    Factor B    Factor C    34.01666667 5.340999698

和情节

情节1

显然,有足够的数据为组factorB中的factorC线画一条平滑线。任何的想法?

林正

我认为这很棘手。通过一些测试和阅读后电流GH代码StatSmooth,我总结我的调查结果如下:

观察结果

  1. geom_smooth()如果任何数据组对AND的观察值太少,则无法在绘图面板中绘制所有平滑线method = "gam" formula = y ~ s(x, k = 3)
  2. 如果该图面分成多个面板,则仅会影响具有不良数据组的面板;
  3. 不会发生这种情况formula = y ~ x(即默认公式);
  4. 这不会发生一些其他的方法(例如"lm""glm")使用默认的公式,但有发生method = "loess";
  5. 如果数据组只有1个观察值,则不会发生这种情况。

我们可以用一些简化的代码重现上面的内容:

# create sample data
n <- 30
set.seed(567)
df.1 <- data.frame( # there is only 1 observation for group == B
  x = rnorm(n), y = rnorm(n),
  group = c(rep("A", n - 1), rep("B", 1)),
  facet = sample(c("X", "Y"), size = n, replace = TRUE))    
set.seed(567)
df.2 <- data.frame( # there are 2 observations for group == B
  x = rnorm(n), y = rnorm(n),
  group = c(rep("A", n - 2), rep("B", 2)),
  facet = sample(c("X", "Y"), size = n, replace = TRUE))

# create base plot
p <- ggplot(df.2, aes(x = x, y = y, color = group)) + 
  geom_point() + theme_bw()

# problem: no smoothed line at all in the entire plot
p + geom_smooth(method = "gam", formula = y ~ s(x, k = 3))

# problem: no smoothed line in the affected panel
p + facet_wrap(~ facet) + 
  geom_smooth(method = "gam", formula = y ~ s(x, k = 3))

# no problem with default formula: smoothed lines in both facet panels
p + facet_wrap(~ facet) + geom_smooth(method = "gam")

# no problem with lm / glm, but problem with loess
p + facet_wrap(~ facet) + geom_smooth(method = "lm")
p + facet_wrap(~ facet) + geom_smooth(method = "glm")
p + facet_wrap(~ facet) + geom_smooth(method = "loess")

# no problem if there's only one observation (instead of two)
p %+% df.1 + geom_smooth(method = "gam", formula = y ~ s(x, k = 3))
p %+% df.1 + facet_wrap(~ facet) + 
  geom_smooth(method = "gam", formula = y ~ s(x, k = 3))

意见1和2的解释:

我认为问题的关键在于中的最后两行StatSmoothcompute_group功能。第一行调用模型的功能(例如stats::glmstats::loessmgcv::gam),用于通过指定的每一组数据帧上aes(group = ...)的映射,而第二行调用包装器之一的周围stats::predict(),以获得平滑的值(以及置信区间,如果适用的话),用于模型。

model <- do.call(method, c(base.args, method.args))
predictdf(model, xseq, se, level)

当参数method = "gam", formula = y ~ s(x, k = 3)仅用于带有两个观察值的数据帧时,将发生以下情况:

model <- do.call(mgcv::gam,
                 args = list(formula = y ~ s(x, k = 3),
                             data = df.2 %>% filter(group == "B" & facet == "X")))

smooth.construct.tp.smooth.spec(object,dk $ data,dk $ knots)中的错误:一个术语的唯一协变量组合少于指定的最大自由度

model,定义为采用的结果的对象do.call(...),甚至尚未创建。代码的最后一行predictdf(...)将抛出错误,因为model不存在。刻面,这会影响所有所做的计算StatSmooth,并且geom_smooth()没有接收到可用的数据来创建在其层中的任何的geom。使用构面时,将针对每个构面分别进行上述计算,因此仅影响有问题数据的构面会受到影响。

意见3和4的解释:

加上上面的内容,如果我们没有指定公式来替换默认值y ~ x,我们将从gam/ lm/获得一个有效的模型对象glm,可以将其传递给ggplot2的未导出predictdf函数以获取预测值的数据帧:

model <- do.call(mgcv::gam, # or stats::lm, stats::glm
                 args = list(formula = y ~ x,
                             data = df.2 %>% filter(group == "B" & facet == "X")))

result <- ggplot2:::predictdf(
  model, 
  xseq = seq(-2, 1.5, length.out = 80), # pseudo range of x-axis values
  se = FALSE, level = 0.95) # default SE / level parameters

loess也将返回一个有效的对象,尽管带有大量警告。但是,将其传递给predictdf将导致错误:

model <- do.call(stats::loess,
                 args = list(formula = y ~ x,
                             data = df.2 %>% filter(group == "B" & facet == "X")))

result <- ggplot2:::predictdf(
  model, 
  xseq = seq(-2, 1.5, length.out = 80), # pseudo range of x-axis values
  se = FALSE, level = 0.95) # default SE / level parameters

predLoess(object $ y,object $ x,newx = if(is.null(newdata))object $ x else if(is.data.frame(newdata))as.matrix(model.frame(delete.response( terms(object)),:外部函数调用中的NA / NaN / Inf(arg 5)

观察说明5:

StatSmoothcompute_group功能从以下内容开始:

if (length(unique(data$x)) < 2) {
      # Not enough data to perform fit
      return(data.frame())
    }

换句话说,如果指定组中只有1个观察值,则StatSmooth立即返回空白数据帧。因此,它将永远不会到达代码的后续部分以引发任何错误。

解决方法:

查明发生问题的地方后,我们可以对compute_group代码进行调整(请参阅带注释和注释掉的部分):

new.compute_group <- function(
  data, scales, method = "auto", formula = y~x, se = TRUE, n = 80, span = 0.75, 
  fullrange = FALSE, xseq = NULL, level = 0.95, method.args = list(), na.rm = FALSE) {
  if (length(unique(data$x)) < 2) return(data.frame()) 
  if (is.null(data$weight)) data$weight <- 1
  if (is.null(xseq)) {
    if (is.integer(data$x)) {
      if (fullrange) {
        xseq <- scales$x$dimension()
      } else {
        xseq <- sort(unique(data$x))
      }
    } else {
      if (fullrange) {
        range <- scales$x$dimension()
      } else {
        range <- range(data$x, na.rm = TRUE)
      }
      xseq <- seq(range[1], range[2], length.out = n)
    }
  }
  if (identical(method, "loess")) method.args$span <- span 
  if (is.character(method)) method <- match.fun(method)
  base.args <- list(quote(formula), data = quote(data), weights = quote(weight))

  # if modelling fails, return empty data frame
  # model <- do.call(method, c(base.args, method.args))
  model <- try(do.call(method, c(base.args, method.args)))
  if(inherits(model, "try-error")) return(data.frame())

  # if modelling didn't fail, but prediction returns NA,
  # also return empty data frame
  # predictdf(model, xseq, se, level)
  pred <- try(ggplot2:::predictdf(model, xseq, se, level))
  if(inherits(pred, "try-error")) return(data.frame())
  return(pred)
}

定义一个使用此版本的新统计图层:

# same as stat_smooth() except that it uses stat = StatSmooth2, rather 
# than StatSmooth
stat_smooth_local <- function(
  mapping = NULL, data = NULL, geom = "smooth", position = "identity", ...,
  method = "auto", formula = y ~ x, se = TRUE, n = 80, span = 0.75,
  fullrange = FALSE, level = 0.95, method.args = list(), na.rm = FALSE,
  show.legend = NA, inherit.aes = TRUE) {
  layer(
    data = data, mapping = mapping, stat = StatSmooth2,
    geom = geom, position = position, show.legend = show.legend,
    inherit.aes = inherit.aes,
    params = list(
      method = method, formula = formula, se = se, n = n,
      fullrange = fullrange, level = level, na.rm = na.rm,
      method.args = method.args, span = span, ...
    )
  )
}

# inherit from StatSmooth
StatSmooth2 <- ggproto(
  "StatSmooth2", ggplot2::StatSmooth,
  compute_group = new.compute_group
)

结果:

我们可以像以前一样处理相同的情况,替换geom_smooth()stat_smooth_local(),并验证在每种情况下都可以看到平滑的geom图层(请注意,有些图层仍会产生错误消息):

# problem resolved: smoothed line for applicable group in the entire plot
p + stat_smooth_local(method = "gam", formula = y ~ s(x, k = 3))

# problem resolved: smoothed line for applicable group in the affected panel
p + facet_wrap(~ facet) + 
  stat_smooth_local(method = "gam", formula = y ~ s(x, k = 3))

# still no problem with default formula
p + facet_wrap(~ facet) + stat_smooth_local(method = "gam")

# still no problem with lm / glm; problem resolved for loess
p + facet_wrap(~ facet) + stat_smooth_local(method = "lm")
p + facet_wrap(~ facet) + stat_smooth_local(method = "glm")
p + facet_grid(~ facet) + stat_smooth_local(method = "loess")

# still no problem if there's only one observation (instead of two)
p %+% df.1 + stat_smooth_local(method = "gam", formula = y ~ s(x, k = 3))
p %+% df.1 + facet_wrap(~ facet) + 
  stat_smooth_local(method = "gam", formula = y ~ s(x, k = 3))

# showing one pair of contrasts here
cowplot::plot_grid(
  p + facet_wrap(~ facet) + ggtitle("Before") +
    geom_smooth(method = "gam", formula = y ~ s(x, k = 3)),
  p + facet_wrap(~ facet) + ggtitle("After") +
    stat_smooth_local(method = "gam", formula = y ~ s(x, k = 3)),
  nrow = 2
)

情节

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用facet_wrap和ggplot2在每个构面内绘制整个数据

使用ggplot2和facet_wrap绘制估计值而无需重新拟合模型

如何在ggplot中使用facet_wrap绘制5点线图和1点barplot

ggplot geom_bar 按组和 facet_wrap 绘制百分比

使用facet_wrap在ggplot2中绘制时间序列数据

ggplot2 facet_wrap在每个构面上绘制点,线段和文本

使用ggplot的facet_wrap和自相关图

如何使用facet_wrap绘制ggplot2,显示每个组的百分比,而不是总百分比?

如何使用facet_wrap拆分列并绘制图形?

如何使用每组行号作为 x 用 `facet_wrap()` 绘制 `geom_point()`?

如何在R中使用facet_wrap并排绘制箱线图?

R使用facet_wrap绘制具有时间间隔的时间序列

将累积数量添加到使用facet_wrap绘制的geom_bar图中

ggplot 在 R 中使用 facet_wrap?

使用独立的 ggplot 和使用 facet_wrap() 创建的 ggplot 创建单个 ggplot 图?

facet_wrap绘制错误的x轴坐标

使用facet_wrap()时无法控制ggplot2中的legend.position

使用ggplot2和facet_wrap显示不同的轴标签

使用ggplot2结合facet_wrap和95%的密度图面积

如何使用facet_wrap`表`所有因子列和ggplot geom_bar?

在ggplot2中使用facet_wrap和scales =“ free”设置单个轴限制

如何使用facet_wrap将NSE和PBIAS结果添加到ggplot中?

在`ggplot`和`ggmap`中使用`facet_wrap`来显示多个图形的问题

ggplot中的geom_vline和facet_wrap错误

GGplot_annotate 和 facet_wrap 函数

通过使用facet_wrap将r平方成ggplot

ggplot在使用`facet_wrap`时添加正态分布

使用facet_wrap时ggplot重新排序更改

在ggplot中使用facet_wrap时缩放y轴