R gist — Plotting the area under the curve with ggplot

Statistics
R
ggplot2
Author

Stefano Coretta

Published

July 4, 2021

knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(ggthemr)
ggthemr("earth")
Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
ℹ Please use the `linewidth` argument instead.
ℹ The deprecated feature was likely used in the ggthemr package.
  Please report the issue to the authors.
Warning: The `size` argument of `element_rect()` is deprecated as of ggplot2 3.4.0.
ℹ Please use the `linewidth` argument instead.
ℹ The deprecated feature was likely used in the ggthemr package.
  Please report the issue to the authors.
x <- 1:11
y <- (1.5:11.5)^2
low <- (0:10)^2
upp <- (3:13)^2
ggplot() +
  aes(x, y) +
  geom_line() +
  geom_ribbon(aes(ymin = low, ymax = upp), alpha = 0.5)

x2 <- c(1:8, NA, NA, NA)
ggplot() +
  aes(x, y) +
  geom_line() +
  geom_ribbon(aes(x = x2, ymin = low, ymax = upp), alpha = 0.5)
Warning: Removed 3 rows containing missing values or values outside the scale range
(`geom_ribbon()`).

x <- seq(-4, 4, by = 0.05)
y <- dnorm(x)
p <- ggplot() +
  aes(x, y) +
  geom_line()
p

p +
  geom_ribbon(
    aes(x = ifelse(x <= -1 , x, NA), ymin = 0, ymax = y),
    fill = "#E84646",
    alpha = 0.4
  )
Warning: Removed 100 rows containing missing values or values outside the scale range
(`geom_ribbon()`).

Citation

BibTeX citation:
@online{coretta2021,
  author = {Coretta, Stefano},
  title = {R Gist — {Plotting} the Area Under the Curve with Ggplot},
  date = {2021-07-04},
  url = {https://stefanocoretta.github.io/posts/2021-07-04-plotting-the-area-under-the-curve/},
  langid = {en}
}
For attribution, please cite this work as:
Coretta, Stefano. 2021. R gist — Plotting the area under the curve with ggplot. https://stefanocoretta.github.io/posts/2021-07-04-plotting-the-area-under-the-curve/.