对于facet_grid中的stat_smooth,ggplot2 se = TRUE取决于if语句

时间:2018-10-17 16:23:24

标签: r ggplot2

我正在尝试获取给定条件的标准误差以绘制在图上。我希望它在某些图形中显示而不在其他图形中显示,并且我试图在stat_smooth中使用if语句来实现此目的:

library(ggplot2)
ggplot(diamonds, aes(depth, price)) + 
  stat_smooth(method="glm", se = ifelse(color == "I", FALSE, TRUE), formula=y~x,
          alpha=0.2, size=1, aes(fill=cut)) +
  facet_grid(.~ color)

但是,它似乎无法识别出颜色变量:

Error in ifelse(color == "I", FALSE, TRUE) : object 'color' not found

我还尝试映射一个变量以保存此true和false值:

library(dplyr)

diamonds <- diamonds %>% mutate(SE = ifelse(color=="I", FALSE, TRUE))

ggplot(diamonds, aes(depth, price, colour=SE)) + 
  stat_smooth(method="glm", se = SE, formula=y~x,
          alpha=0.2, size=1, aes(fill=cut)) +
  facet_grid(.~ color)

2 个答案:

答案 0 :(得分:2)

您可以手动通过以下方式实现所需的目标:

library(ggplot2)
library(gridExtra)

colors <- unique(diamonds$color)
do.call(grid.arrange, lapply(colors, function(color) {
  ggplot(diamonds[diamonds$color == color,], aes(depth, price)) + 
    stat_smooth(method="glm", se = (color != "I"), formula=y~x,
                alpha=0.2, size=1, aes(fill=cut)) +
    scale_x_continuous(limits=c(40, 80)) +
    scale_y_continuous(limits=c(0,10000)) -> gg
  if (color != colors[length(colors)]) gg + theme(legend.position = "none") else gg
}))

并使用<{Add a common Legend for combined ggplots>之类的东西进行骇客入侵,以使普通图例不出现在情节中,并使情节保持一致。

答案 1 :(得分:2)

保持这个单独的账单很长。您还可以编写stat_smooth/StatSmooth的自定义版本:

stat_smooth2 <- 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,
      ...
    )
  )
}

StatSmooth2 <- ggproto("StatSmooth", Stat,

  setup_params = function(data, params) {
    if (identical(params$method, "auto")) {
      # Use loess for small datasets, gam with a cubic regression basis for
      # larger. Based on size of the _largest_ group to avoid bad memory
      # behaviour of loess
      max_group <- max(table(interaction(data$group, data$PANEL, drop = TRUE)))

      if (max_group < 1000) {
        params$method <- "loess"
      } else {
        params$method <- "gam"
        params$formula <- y ~ s(x, bs = "cs")
      }
      message("`geom_smooth()` using method = '", params$method, 
              "' and formula '", deparse(params$formula), "'")
    }
    if (identical(params$method, "gam")) {
      params$method <- mgcv::gam
    }

    params
  },

  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) {
      # Not enough data to perform fit
      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)
      }
    }
    # Special case span because it's the most commonly used model argument
    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))
    model <- do.call(method, c(base.args, method.args))

    se <- data$secol[1] != "I"

    ggplot2:::predictdf(model, xseq, se, level)
  },

  required_aes = c("x", "y", "secol")
)

然后做你想做的事

library(ggplot2)
ggplot(diamonds, aes(depth, price)) + 
  stat_smooth2(method="glm", formula=y~x,
          alpha=0.2, size=1, aes(fill=cut, secol = color)) + # << NOTE secol
  facet_grid(.~ color)

给出:

enter image description here

这比为传奇传奇窃取杂物要少得多。