1
votes

The code below plots step functions of increasing accuracy toward the underlying polynomial or exponential curve. I am trying to add a curve to my plot that goes through the bottom of each step that I have added.

The commented lines are different attempts that I have tried, but nothing goes exactly through all of the bottom corners of each step down. Is anyone able to help me achieve this? Any help would be greatly appreciated.

 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

1 Answers

0
votes

I ended up re-doing the initial functions and made it all match up:

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