ggplot2||图层添加阴影区域geom_rect/ribbon/area/abline/polygon/abline

图已经做出来了!
但是要突出某一区域,怎么办?

geom_rect()/annotate() , geom_abline() ,
geom_ribbon() , geom_area() ,
geom_density() , geom_polygon() , ...

1. 规则阴影

  • 两平行线之间的阴影区
  • 参考 ggplot2 - shade area between two vertical lines
    library(ggplot2)
    data(mtcars)
    ggplot(mtcars, aes(x = drat, y = hp)) + 
      geom_line() + 
      geom_rect(aes(xmin=3, xmax=4.2, ymin=-Inf, ymax=Inf),fill='#FF3300',alpha = .02)
      #annotate("rect", xmin = 3, xmax = 4.2, ymin=-Inf, ymax=Inf,fill='#FF3300', alpha = .02)
    ggplot(df1) + 
      geom_line(aes(x, y), linetype = 2) +
      geom_abline(slope = seq(1.6, 2.4, 0.0001), color = "grey60", intercept = 0) +
      geom_abline(slope = 2, intercept = 0) +
      #coord_cartesian(ylim = c(0, 200), xlim = c(0, 100)) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0))
    
    library(ggplot2)
    df2 <- data.frame(x=1, y=1)
    df_poly <- data.frame( x=c(-Inf, Inf, -Inf), y=c(-Inf, Inf, Inf))
    ggplot(df2, aes(x, y)) + 
      geom_blank() + 
      geom_abline(slope=1, intercept=0) + 
      geom_polygon(data=df_poly, aes(x, y), fill="blue", alpha=0.2)
    x <- mtcars$drat
    y <- mtcars$hp
    df3 <- data.frame(x=x, y=y, lower = (y+runif(32, -200, -100)), upper = (y+runif(32, 100, 200)))
    ggplot(df3,aes(x = x, y = y)) + 
      geom_line() + 
      #geom_rect(aes(xmin=3, xmax=4.2, ymin=-Inf, ymax=Inf), fill='#FF3300', alpha = .02)
      #annotate("rect", xmin = 3, xmax = 4.2, ymin=-Inf, ymax=Inf, fill='#FF3300', alpha = .2) +
      geom_ribbon(aes(ymin=lower, ymax=upper, x=x), fill = "red", alpha = 0.3)
    ggplot(data = mtcars, aes(x = drat, y = hp)) + 
      #geom_smooth(color="red", formula = y ~ x) + 
      geom_smooth(method = "lm", #se=FALSE, 
                  fill="#33CCCC",alpha=.25, formula = y ~ x) +   
      geom_point() +
      scale_x_continuous("drat")
    x  <- seq(-7, 10, length = 200)
    y1 <- dnorm(x, mean = 0,sd = 1)
    y2 <- dnorm(x, mean = 3,sd = 2)
    df4 <- data.frame(x, y1, y2)
    ggplot(df4, aes(x = x)) +
      geom_line(aes(y = y1), colour = 'blue') +geom_line(aes(y = y2), colour = 'red') +
      geom_area(aes(y = pmin(y1, y2)), fill = 'gray60')