代码之家  ›  专栏  ›  技术社区  ›  Krantz

使用ggplot基于x值应用透明背景划分打印区域

  •  0
  • Krantz  · 技术社区  · 6 年前

    如果您能将下面的透明背景色应用于 根据x值将绘图区域分为两部分,如下图所示(垂直分割)。

    以下是我的示例数据和代码:

    mtcars$cyl <- as.factor(mtcars$cyl)
    ggplot(mtcars, aes(x=wt, y=mpg, color=cyl)) +
      geom_point() + 
      theme(legend.position="none")+
      geom_smooth(method=lm, se=FALSE, fullrange=TRUE)
    

    下面是我想要复制的图,图例说明了我想要实现的更改:

    enter image description here

    1 回复  |  直到 5 年前
        1
  •  1
  •   Anonymous coward    6 年前

    geom_ribbon ,并设置 ymin ymax 随你的便。

    library(tidyverse)
        mtcars$group <- ifelse(mtcars$wt <= 3.5, "<= 3.5", "> 3.5")
    mtcars <- arrange(mtcars, wt)
    mtcars$group2 <- rleid(mtcars$group)
    mtcars_plot <- head(do.call(rbind, by(mtcars, mtcars$group2, rbind, NA)), -1)
    mtcars_plot[,c("group2","group")] <- lapply(mtcars_plot[,c("group2","group")], na.locf)
    mtcars_plot[] <- lapply(mtcars_plot, na.locf, fromLast = TRUE)
    
    ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
      geom_point() +
      geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
      geom_ribbon(aes(ymin = mpg *.75, ymax = mpg * 1.25, fill = group), alpha = .25) +
      labs(fill = "Weight Class")
    

    :

    使用 你必须事先用计算机计算它们 lm predict .

    mtmodel <- lm(mpg ~ wt, data = mtcars)
    mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
    mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]
    

    mtcars . 然后用计算出的边界绘制。

    ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
      geom_point() +
      geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
      geom_ribbon(aes(ymin = Low, ymax = High, fill = group), alpha = .25) +
      labs(fill = "Weight Class") +
      scale_fill_manual(values = c("red", "orange"), name = "fill")