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)
geom_rect_plot
  • 两相交直线(两斜率不同直线)之间的阴影区--geom_abline()

参考 geom_ribbon set slope & intercept

library(ggplot2)
df1 <- data.frame(x = 1:100, y = 2*(1:100))

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))
geom_abline_plot
  • 置信区间(参考下文geom_ribbon())

  • 其他。。。

参考 任意规则阴影?

  • 拿一个来举例--geom_polygon
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)
geom_polygon_plot

2. 不规则阴影

  • 置信区间--geom_ribbon()

参考 Legend with geom_line and geom_ribbon

library(ggplot2)
data(mtcars)

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)
geom_ribbon_plot
  • 线性拟合--lm()
library(ggplot2)

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")
lm_fit
  • 面积图(曲线之间)--geom_area()

参考地址找不到了就这个吧

library(ggplot2)

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')
geom_area

后记

本来我只是想加一个两个垂线之间的阴影就像第一种所示的那样,一搜搜到这么多的方法,那就

。。。。学代码!!

分类不止如此!方法也不止如此!按需求索。。。

更详尽的作图方法可以参考ggplot2高效实用指南 (可视化脚本、工具、套路、配色)

PS:

三三两两 浑浑噩噩
愿岁月静好且可期

2019/12/30 11:52

你可能感兴趣的:(ggplot2||图层添加阴影区域geom_rect/ribbon/area/abline/polygon/abline)