在ggplot2中创建范围(走廊)图

时间:2018-06-18 16:58:27

标签: r ggplot2

鉴于r-statistics网站提供的示例,我想修改它创建范围图

实施例

# 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

期望的结果

Example range plot

的尝试

"white"

将一个系列颜色设置为白色,很接近,但我想让网格可见。控制图例可以在以后轻松完成。

attempt 1

1 个答案:

答案 0 :(得分:1)

您确定需要使用geom_ribbon

从文件中采用:

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