【问题标题】:ggplot2 Create shaded area with gradient below curveggplot2 创建曲线下方渐变的阴影区域
【发布时间】:2020-08-29 16:02:03
【问题描述】:

我想使用 ggplot 创建下面的图。 有谁知道任何在折线图下方创建阴影区域的geom? 谢谢

【问题讨论】:

标签: r ggplot2


【解决方案1】:

我认为您只是在寻找geom_area。但是,我认为仅使用 ggplot 来查看我们与您尝试生成的图表有多接近可能是一个有用的练习:

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


数据

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)

【讨论】:

  • @Tjebo 谢谢。我应该对此表示赞同!我喜欢你所有的建议并采纳了它们。现在看起来很近了。
  • @AllanCameron 感谢艾伦,这对我的预期来说有点矫枉过正,但是您创建了完全相同的图表!我很感动。事实上,样条插值对于我目前的工作也非常有用。再次感谢!
  • Teun 的另一个破解者,@tjebo。我们一直在合作开发一个包,以在 ggplot 中正确实现弯曲文本。希望它离生产标准不会太远:github.com/AllanCameron/geomtextpath
  • 我已经看到了。太棒了!
猜你喜欢
  • 1970-01-01
  • 2018-06-21
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多