Konrad
Konrad

Reputation: 18585

Creating range (corridor) plot in ggplot2

Given the example available through r-statistics website, I would like to modify it create a range plot

Example

# Notes -------------------------------------------------------------------

# Stacked are chart
# Source: http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html#Stacked%20Area%20Chart

# Graphic -----------------------------------------------------------------

library(ggplot2)
library(lubridate)
theme_set(theme_bw())

df <- economics[, c("date", "psavert", "uempmed")]
df <- df[lubridate::year(df$date) %in% c(1967:1981),]

# labels and breaks for X axis text
brks <- df$date[seq(1, length(df$date), 12)]
lbls <- lubridate::year(brks)

# plot
ggplot(df, aes(x = date)) +
    geom_area(aes(y = psavert + uempmed, fill = "psavert")) +
    geom_area(aes(y = uempmed, fill = "uempmed")) +
    labs(
        title = "Area Chart of Returns Percentage",
        subtitle = "From Wide Data format",
        caption = "Source: Economics",
        y = "Returns %"
    ) +  # title and caption
    scale_x_date(labels = lbls, breaks = brks) +  # change to monthly ticks and labels
    scale_fill_manual(name = "",
                      values = c("psavert" = "#00ba38", "uempmed" = "#f8766d")) +  # line color
    theme(panel.grid.minor = element_blank())  # turn off minor grid

Desired results

Example range plot

Attempts

"white"

Setting one series colour to white, is close but I would like to make the grid visible. Controlling legend could be easily done later.

attempt 1

Upvotes: 2

Views: 314

Answers (1)

liborm
liborm

Reputation: 2724

You sure need to use geom_ribbon.

Adopted from the docs:

library(tidyverse)

data.frame(year = 1875:1972, level = as.vector(LakeHuron)) %>%
  ggplot(aes(year)) +
  geom_ribbon(aes(ymin = level - 1, ymax = level + 1), fill = "grey70") +
  geom_line(aes(y = level))

Upvotes: 2

Related Questions