ggplot2创建曲线下方的渐变阴影区域

时间:2020-05-13 12:43:14

标签: r ggplot2

我想使用ggplot创建以下图。 有人知道在折线图下方创建阴影区域的任何geom吗? 谢谢 enter image description here

1 个答案:

答案 0 :(得分:4)

我认为您只是在寻找geom_area。但是,我认为这可能是一个有用的练习,它仅使用ggplot来了解我们与您尝试生成的图形之间的距离:

enter image description here

非常接近。这是产生它的代码:


数据

library(ggplot2)
library(lubridate)

# Data points estimated from the plot in the question:
points <- data.frame(x = seq(as.Date("2019-10-01"), length.out = 7, by = "month"),
                     y = c(2, 2.5, 3.8, 5.4, 6, 8.5, 6.2))

# Interpolate the measured points with a spline to produce a nice curve:
spline_df   <- as.data.frame(spline(points$x, points$y, n = 200, method = "nat"))
spline_df$x <- as.Date(spline_df$x, origin = as.Date("1970-01-01"))
spline_df   <- spline_df[2:199, ]

# A data frame to produce a gradient effect over the filled area:
grad_df <- data.frame(yintercept = seq(0, 8, length.out = 200), 
                      alpha = seq(0.3, 0, length.out = 200))

标签功能

# Turns dates into a format matching the question's x axis
xlabeller <- function(d) paste(toupper(month.abb[month(d)]), year(d), sep = "\n")

# Format the numbers as per the y axis on the OP's graph
ylabeller <- function(d) ifelse(nchar(d) == 1 & d != 0, paste0("0", d), d)

图解

ggplot(points, aes(x, y)) + 
  geom_area(data = spline_df, fill = "#80C020", alpha = 0.35) + 
  geom_hline(data = grad_df, aes(yintercept = yintercept, alpha = alpha), 
             size = 2.5, colour = "white") +
  geom_line(data = spline_df, colour = "#80C020", size = 1.2) +
  geom_point(shape = 16, size = 4.5, colour = "#80C020") +
  geom_point(shape = 16, size = 2.5, colour = "white") +
  geom_hline(aes(yintercept = 2), alpha = 0.02) +
  theme_bw() +
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.minor.y = element_blank(),
        panel.border       = element_blank(),
        axis.line.x        = element_line(),
        text               = element_text(size = 15),
        plot.margin        = margin(unit(c(20, 20, 20, 20), "pt")),
        axis.ticks         = element_blank(),
        axis.text.y        = element_text(margin = margin(0,15,0,0, unit = "pt"))) +
  scale_alpha_identity() + labs(x="",y="") +
  scale_y_continuous(limits = c(0, 10), breaks = 0:5 * 2, expand = c(0, 0),
                     labels = ylabeller) +
  scale_x_date(breaks = "months", expand = c(0.02, 0), labels = xlabeller)