在ggplot中添加一条穿过预定点的指数线

时间:2018-11-13 02:59:19

标签: r ggplot2

下面的代码绘制了朝着基础的多项式或指数曲线提高精度的阶跃函数。我正在尝试向曲线添加一条曲线,该曲线穿过添加的每个步骤的底部。

注释的行是我尝试过的不同尝试,但是没有准确地贯穿每一步的所有下角。有谁能够帮助我实现这一目标?任何帮助将不胜感激。

 library(ggplot2)

 X1 <- seq(1, 5, by=0.25)
 Y1 <- (0.74 * X^(-2)+0.25)*100
 sm <- data.frame(X1, Y1)

 X2 <- sort(rep(seq(1, 5, by=0.5), 2))[-18]
 Y2 <- sort(rep(Y1[1:17 %% 2 == 1], 2), decreasing = T)[-18]
 med <- data.frame(X1, Y2)

 X3 <- sort(rep(seq(1,5), 4))[1:17]
 Y3 <- sort(rep(Y1[c(1, 5, 9, 13, 17)], 4), decreasing = T)[1:17]
 lg <- data.frame(X1, Y3)

 ggplot() +
    #stat_function(data=sm, mapping = aes(x = X), fun = function(x) {exp(-1*x)*100+28}) +
    #geom_curve(aes(x=1, xend=5, y=99, yend=28), ncp = 17) +
    #geom_smooth(data = sm, aes(x=X1, y=Y1), method="lm", formula = y ~ poly(x,2), se=F, color= "black", fullrange=T) +
    #geom_smooth(data = sm, aes(x=X1, y=Y1), method="lm", formula = (y ~ exp(-1.9*x)), se=F, color= "black", fullrange=T) +
    scale_y_continuous(name="Overall Survival (%)", limits=c(0, 100)) +
    scale_x_continuous(breaks = seq(from=1, to=5, by=0.25), name = "Survival Time (years)") +
    geom_step(colour = "red",    size = 1, data = lg,  aes(x=X1, y=Y3)) +
    geom_step(colour = "purple", size = 1, data = med, aes(x=X1, y=Y2)) +
    geom_step(colour = "orange", size = 1, data = sm,  aes(x=X1, y=Y1)) +
    theme_classic()

1 个答案:

答案 0 :(得分:1)

我最终重新做了初始功能,并使其全部匹配:

MyFunction <- function(x) {100*exp(-(1/4)*x)}

Xyearly <- c(0:5)
Yyearly <- MyFunction(Xyearly)
Yearly <- data.frame(x=Xyearly, y=Yyearly)

X6monthly <- c(0:10/2)
Y6monthly <- MyFunction(X6monthly)
Month6 <- data.frame(x=X6monthly, y=Y6monthly)

X3monthly <- c(0:15/3)
Y3monthly <- MyFunction(X3monthly)
Month3 <- data.frame(x=X3monthly, y=Y3monthly)

X1monthly <- c(0:60/12)
Y1monthly <- MyFunction(X1monthly)
Month1 <- data.frame(x=X1monthly, y=Y1monthly)

ggplot() +
 stat_function(data=data.frame(x = 0), mapping = aes(x = x), fun = MyFunction, size=1.2) +
 scale_y_continuous(name="Overall Survival (%)", limits=c(0, 100)) +
 scale_x_continuous(breaks = seq(from=0, to=5, by=0.5), name = "Survival Time (years)") +
 geom_step(colour = "red",    size = 1, data = Yearly,  aes(x=x, y=y)) +
 geom_step(colour = "purple",    size = 1, data = Month6,  aes(x=x, y=y)) +
 geom_step(colour = "orange",    size = 1, data = Month3,  aes(x=x, y=y)) +
 geom_step(colour = "limegreen",    size = 1, data = Month1,  aes(x=x, y=y))