【问题标题】:ggplot2: How to shade an area above a function curve and below a line?ggplot2:如何对函数曲线上方和直线下方的区域进行着色?
【发布时间】:2017-07-25 11:23:15
【问题描述】:

所以我有一个这样的数据框:

a_data <-
  data.frame(
    f = f,
    alpha = alpha,
    asymptote = alpha_1_est)

还有这样的函数:

a_formula <- function(x) {
  0.7208959 - 0.8049132 * exp(-21.0274 * x)}

我将它们与 ggplot2 一起使用:

ggplot(a_data, aes(x = f, y = alpha)) + 

geom_point() +

#function curve
stat_function(fun = a_formula,
              color = "red") +

#asymptote of alpha
geom_hline(
  yintercept = asymptote,
  linetype = "longdash",
  color = "blue")

产生这样的情节:

我想要但找不到方法是对y 轴、函数曲线(红色)和渐近线(虚线)之间的区域进行着色,如下所示:

我曾尝试在其中挤压丝带或多边形,但无法正常工作 - 可能是因为我想在曲线上方而不是下方(下方可以正常工作) .

这是数据框的样子:

> head(a_data)
     f       alpha asymptote
1 0.01 0.007246302 0.7208959
2 0.03 0.374720198 0.7208959
3 0.05 0.484362949 0.7208959
4 0.07 0.540090209 0.7208959
5 0.09 0.625383303 0.7208959
6 0.11 0.590898201 0.7208959

附:我对 stackoverflowing 还很陌生,所以如果我违反了任何约定或以其他方式弄乱了问题,请不要犹豫指出。

【问题讨论】:

  • 你试过geom_ribbon吗?也许看看this
  • 你能运行dput(a_data) 并粘贴输出吗?它应该足够小并且可以完全复制。顺便说一句:您已经完成了 ++gd 的工作来构建问题并设置示例。但是,在您的a_data 输出中没有f,并且geom_hline() 调用将无法找到asymptote,除非您打算将它放在aes()
  • @hrbrmstr,实际上dput(a_data) 的输出很大,所以我不确定将它添加到问题中是否是个好主意(不能只是将其粘贴到评论中,它太大了)。但我明白你的意思——下次我问问题时,我会更仔细地考虑繁殖。感谢您的宝贵时间!
  • @simone 我有,我也看到了你链接的问题。对我帮助不大,但也许我需要仔细看看。谢谢!

标签: r plot ggplot2


【解决方案1】:

下面的例子展示了geom_ribbon如何方便地用于为水平线和曲线之间的区域着色。

df1 <- structure(list(x = c(0.01, 0.03, 0.05, 0.07, 0.09, 0.11), y = c(0.007246302, 
0.374720198, 0.484362949, 0.540090209, 0.625383303, 0.590898201
), asymptote = c(0.7208959, 0.7208959, 0.7208959, 0.7208959, 
0.7208959, 0.7208959)), .Names = c("x", "y", "asymptote"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

a_formula <- function(x) { 0.7208959 - 0.8049132*exp(-21.0274*x) }

xs <- seq(min(df1$x),max(df1$x),length.out=100)
ysmax <- rep(0.7208959, length(xs))
ysmin <- a_formula(xs)
df2 <- data.frame(xs, ysmin, ysmax)

library(ggplot2)
ggplot(data=df1) + geom_point(aes(x=x, y=y)) +
geom_line(aes(x=x, y=asymptote), lty=2, col="blue", lwd=1) +
stat_function(fun = a_formula, color="red", lwd=1) +
geom_ribbon(aes(x=xs, ymin=ysmin, ymax=ysmax), data=df2, fill="#BB000033")

【讨论】:

  • 感谢您花时间写一个答案!它似乎可以解决问题,等我测试完再回来。
猜你喜欢
  • 2012-09-07
  • 2012-08-27
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
相关资源
最近更新 更多