ggplot2:如何在函数曲线上方和直线下方填充颜色?

5

So I have a dataframe like this:

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

这将产生如下图所示的绘图: basic plot 我想做但找不到方法的是在y轴、函数曲线(红色)和渐近线(虚线)之间填充区域,就像这样: shaded plot 我尝试过在那里挤入一个带状物或多边形,但它不能正确地工作 - 可能是因为我想要在曲线上方着色,而不是下方(下方可以正常工作)。
这是数据框的外观:
> 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

附言:我在Stack Overflow上比较新,所以如果我违反了任何规定或者弄乱了问题,请不要犹豫地指出来。


你尝试过geom_ribbon吗?也许可以看一下这个链接:https://dev59.com/v14b5IYBdhLWcg3w31BA。 - simone
1
你能运行 dput(a_data) 并粘贴输出吗?它应该足够小,可以完全复制。顺便说一句:你在构建问题和设置示例方面做得非常好。不过,在你的 a_data 输出中没有 f,并且 geom_hline() 调用将无法找到 asymptote,除非你是想在 aes() 中使用它。 - hrbrmstr
@hrbrmstr,实际上dput(a_data)的输出非常大,所以我不确定将其添加到问题中是否是一个好主意(不能只将其粘贴到评论中,因为它太大了)。但我理解你的观点-下次我会更加仔细地考虑如何重现。谢谢你的时间! - somevasya
@simone 我看过了,也看到了你提供的链接。但是对我没有太大帮助,也许我需要仔细再看一下。谢谢! - somevasya
1个回答

8
下面的示例展示了如何方便地使用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")

enter image description here


谢谢你抽出时间写下答案!看起来这个方法很有效,我测试完后会回来的。 - somevasya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接