geom_ribbon()

R for Pleasure

Nguyen Chi Dung

Introduction

geom_ribbon() displays a y interval defined by ymin and ymax. geom_area() is a special case of geom_ribbon, where the ymin is fixed to 0.

# Create data set: 
rm(list = ls())
library(tidyverse)
huron <- data.frame(year = 1875:1972, 
                    level = LakeHuron)

# Set theme: 
theme_set(theme_minimal())

# Plot 1: 
huron %>% 
  ggplot(aes(year, level)) + 
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "grey90") + 
  geom_line(aes(year, level + 1), color = "grey30", size = 0.1) + 
  geom_line(aes(year, level - 1), color = "grey30", size = 0.1) +   
  geom_line(color = "firebrick", size = 1)

# Plot 2: 
huron %>% 
  ggplot(aes(year, level)) + 
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "steelblue2") + 
  geom_line(color = "firebrick", size = 1)

An Application of Using geom_ribbon()

# Set demand and supply funtions: 
demand <- function(q) {(q - 10)^2}
supply <- function(q) {q^2 + 2*q + 8}

# Set a range of price: 
x <- 0:5

# Equilibrium quantity: 
q <- uniroot(function(x) demand(x) - supply(x), range(x))$root

# Equilibrium price: 
p <- supply(q)

# Make a draft plot: 

ggplot() +
  stat_function(aes(x, color = "Demand"), fun = demand, size = 1) +
  stat_function(aes(x, color = "Supply"), fun = supply, size = 1) + 
  annotate("point", x = q, y = p, color = "grey10") + 
  annotate("segment", x = q, xend = q, y = 0, yend = p,
           linetype = "dashed", color = "grey30") +
  annotate("segment", x = 0, xend = q, y = p, yend = p,
           linetype = "dashed", color = "grey30") ->> chart
  
# Adjust plot: 
z <- seq(0, q, 0.01)

chart + 
  geom_ribbon(aes(x = z, ymin = supply(z), ymax = p, fill = "Producer surplus"), alpha = 0.15) +
  geom_ribbon(aes(x = z, ymin = p, ymax = demand(z), fill = "Consumer surplus"), alpha = 0.15) + 
  labs(x = "Quantity", y = "Price", 
       title = "An Example of Using geom_ribbon() for Making\na Cunsumer and Producer Surplus Plot") + 
  scale_x_continuous(expand = c(0, 0), breaks = q, labels = "q*") +
  scale_y_continuous(expand = c(0, 0), breaks = p, labels = "p*") + 
  theme_classic() + 
  theme(panel.grid = element_blank(),
        legend.position = c(0.95, 0.95), 
        legend.justification = c(1, 1),
        legend.spacing = unit(0, "cm"), 
        legend.margin = margin(0, 0, 0, 0, "cm")) + 
  scale_fill_manual(values = c("purple", "orange"), name = "") + 
  scale_color_manual(values = c("purple", "orange"), name = "")