r - ggplot2:如何为函数曲线上方和线下方的区域着色?

标签 r plot ggplot2

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

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

附言我对 stackoverflowing 还很陌生,所以如果我违反了任何约定或以其他方式搞砸了问题,请毫不犹豫地指出来。

最佳答案

下面的例子展示了 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

关于r - ggplot2:如何为函数曲线上方和线下方的区域着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301798/

相关文章:

r - 聚合/Group_by R中的第二个最小值

python - 在 Python 中制作随机 3-D 形状

python - 使用 matplotlib 中样本的标签为散点图创建图例

r - 用ggplot避开点和误差线

r - 在带有因子变量的 stat_bin 中使用密度

r - 在 LSF 中指定作业数组

r - 使用 indexOut 的插入符和自定义验证集产生奇怪的结果

r - 使用 ggplot2 绘制多条正态曲线,无需硬编码均值和标准差

r - R 中的一切都是向量吗?

c++ - 如何使用Qt/QwtPlot设置固定轴间隔?