Search code examples
rplotsurvival-analysis

Change color in basic plot function R when working with data of special class (stdCoxph)


I normally do all my plotting using ggplot but now I am working with standardized survival curves using a package called stdCoxph. My question is: Does anyone know how to change the color and thickness of these lines. I have tried to use col and lwd, but it does not change anything. See reproducible example below:

#Load packages:
if(!require(stdReg)){install.packages("stdReg", dependencies=TRUE)}
library(stdReg)
library(survival)


n <- 1000
Z <- rnorm(n)
X <- rnorm(n, mean=Z)
Tm <- rexp(n, rate=exp(X+Z+X*Z)) #survival time
C <- rexp(n, rate=exp(X+Z+X*Z)) #censoring time
U <- pmin(Tm, C) #time at risk
D <- as.numeric(Tm < C) #event indicator
dd <- data.frame(Z, X, U, D)
fit <- coxph(formula=Surv(U, D)~ X*Z, data=dd, method="breslow")
# in R formulas ~X*C will be interpreted as ~X+Z+X:Z
fit.std <- stdCoxph(fit=fit, data=dd, X="X", x=seq(-1,1,0.5), t=1:5)
print(summary(fit.std, t=3))
plot(fit.std)

Solution

  • col is hard coded but the other plot parameters can be modified with par :

    opar <- par(lwd = 3)
    plot(std.fit)
    par(opar) # reset back
    

    To change the colors redefine plot.stdCoxph adding a colors argument. This makes a copy of plot.stdCoxph which calls a local copy of lines and legend that use the specified colors.

    plot.stdCoxph <- function(x, ..., colors = seq_along(x)) {
      lines <- function(x, ..., col) graphics::lines(x, ..., col = colors[col])
      legend <- function(x, ..., col) graphics::legend(x, ..., col = colors[col])
      plot.stdCoxph <- stdReg:::plot.stdCoxph
      environment(plot.stdCoxph) <- environment()
      plot.stdCoxph(x, ...)
    }
    
    plot(fit.std, colors = rainbow(5)) # test
    

    You could consider contacting the maintainer of the package and ask if they could provide similar functionality without this workaround.