Introduction

In this vignette, we describe the plot method for objects of class singleEventCB which is obtained from running the fitSmoothHazard function. There are currently two types of plots: hazard functions and hazard ratios. We describe each one in detail below. Note that the plot method has only been properly tested for family="glm".

Hazard Function

The hazard function plots require the visreg package.

To illustrate hazard function plots, we will use the breast cancer dataset which contains the observations of 686 women taken from the TH.data package. This dataset is also available from the casebase package. In the following, we will show different hazard functions for different combinations of continuous, binary variables as well as their interactions.

library(casebase)
#> See example usage at http://sahirbhatnagar.com/casebase/
library(visreg)
library(splines)
library(ggplot2)
data("brcancer")
str(brcancer)

One binary predictor, no interactions

We first fit a main effects only model with a spline on log(time) and hormonal therapy as main effects.

mod_cb <- fitSmoothHazard(cens ~ ns(log(time), df = 3) + hormon,
                          data = brcancer,
                          time = "time")
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(mod_cb)
#> 
#> Call:
#> glm(formula = formula, family = binomial, data = sampleData)
#> 
#> Deviance Residuals: 
#>     Min       1Q   Median       3Q      Max  
#> -0.1804  -0.1586  -0.1488  -0.1254   3.8371  
#> 
#> Coefficients:
#>                        Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)            -86.0897    18.6481  -4.617 3.90e-06 ***
#> ns(log(time), df = 3)1  52.1851    12.2416   4.263 2.02e-05 ***
#> ns(log(time), df = 3)2 151.2105    36.2450   4.172 3.02e-05 ***
#> ns(log(time), df = 3)3  31.5950     7.4983   4.214 2.51e-05 ***
#> hormon                  -0.3526     0.1256  -2.808  0.00498 ** 
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3354.9  on 30198  degrees of freedom
#> Residual deviance: 3277.6  on 30194  degrees of freedom
#> AIC: 3287.6
#> 
#> Number of Fisher Scoring iterations: 10

Hazard functions on separate plots

All arguments needed for the hazard function plots are supplied through the hazard.params argument. This is a named list of arguments which will override the defaults passed to visreg::visreg(). The default arguments are list(fit = x, trans = exp, plot = TRUE, rug = FALSE, alpha = 1, partial = FALSE, overlay = TRUE). For example, if you want a 95% confidence band, specify hazard.params = list(alpha = 0.05). For a complete list of options, please see the visreg vignettes.

We first plot the hazard as a function of time, for hormon = 0 and hormon = 1. This is achieved by specifying the xvar argument, as well as the cond argument. The cond argument must be provided as a named list. Each element of that list specifies the value for one of the terms in the model; any elements left unspecified are filled in with the median/most common category. Note that even though we fit the log(time), we must specify time in the xvar argument.

par(mfrow = c(1, 2))
plot(mod_cb,
     hazard.params = list(xvar = "time",
                          cond = list(hormon = 0),
                          alpha = 0.05,
                          main = "No Hormonal Therapy Hazard Function"))

plot(mod_cb,
     hazard.params = list(xvar = "time",
                          cond = list(hormon = 1),
                          alpha = 0.05,
                          main = "Hormonal Therapy Hazard Function"))

Hazard functions on same plots

Alternatively, we can plot the hazard functions on the same plot. This is accomplished with the by argument:

plot(mod_cb,
     hazard.params = list(xvar = "time",
                          by = "hormon",
                          alpha = 0.05,
                          ylab = "Hazard"))

Note that if we want to extract the data used to construct the plot, e.g. to create our own, we simply assign the call to plot to an object (we may optionally set plot=FALSE in the hazard.params argument as to not print any plots):

plot_results <- plot(mod_cb,
     hazard.params = list(xvar = "time",
                          by = "hormon",
                          alpha = 0.10,
                          ylab = "Hazard",
                          plot = FALSE))
head(plot_results$fit)
#>           time hormon offset cens    visregFit    visregLwr    visregUpr
#> 1   0.01303855      0      0    0 4.090120e-38 1.951746e-51 8.571342e-25
#> 2  26.43898256      0      0    0 2.928452e-07 1.911024e-08 4.487557e-06
#> 3  52.86492658      0      0    0 7.551555e-06 1.667592e-06 3.419661e-05
#> 4  79.29087059      0      0    0 3.441026e-05 1.317768e-05 8.985394e-05
#> 5 105.71681460      0      0    0 8.414268e-05 4.395654e-05 1.610680e-04
#> 6 132.14275862      0      0    0 1.511722e-04 9.551728e-05 2.392556e-04

ggplot2 version

The function is flexible because you may leverage ggplot2 just by specifying gg = TRUE, the plot will return a ggplot object:

gg_object <- plot(mod_cb,
                  hazard.params = list(xvar = "time",
                                       by = "hormon",
                                       alpha = 0.20, # 80% CI
                                       ylab = "Hazard",
                                       gg = TRUE))
attr(gg_object,"class")
#> [1] "gg"     "ggplot"

Now we can use it downstream for any plot while leveraging the entire ggplot2 ecosystem of packages and functions:

gg_object +
  theme_minimal()+
  theme(legend.position = "bottom") +
  labs(title = "Casebase") +
  scale_x_continuous(n.breaks = 10)

One binary predictor with interaction

Next, we fit an interaction model with a time-varying covariate, i.e. to test the hypothesis that the effect of hormonal therapy on the hazard varies with time.

mod_cb_tvc <- fitSmoothHazard(cens ~ hormon * ns(log(time), df = 3),
                              data = brcancer,
                              time = "time")
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(mod_cb_tvc)
#> 
#> Call:
#> glm(formula = formula, family = binomial, data = sampleData)
#> 
#> Deviance Residuals: 
#>     Min       1Q   Median       3Q      Max  
#> -0.1820  -0.1600  -0.1446  -0.1251   3.7802  
#> 
#> Coefficients:
#>                               Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)                    -59.824     15.005  -3.987  6.7e-05 ***
#> hormon                         -24.603     33.783  -0.728 0.466446    
#> ns(log(time), df = 3)1          34.897      9.819   3.554 0.000379 ***
#> ns(log(time), df = 3)2         100.657     29.341   3.431 0.000602 ***
#> ns(log(time), df = 3)3          20.393      5.934   3.437 0.000589 ***
#> hormon:ns(log(time), df = 3)1   16.064     22.286   0.721 0.471010    
#> hormon:ns(log(time), df = 3)2   47.045     65.702   0.716 0.473971    
#> hormon:ns(log(time), df = 3)3    9.949     13.421   0.741 0.458506    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3354.9  on 30198  degrees of freedom
#> Residual deviance: 3274.3  on 30191  degrees of freedom
#> AIC: 3290.3
#> 
#> Number of Fisher Scoring iterations: 11

Now we can easily plot the hazard function over time for each hormon group:

plot(mod_cb_tvc,
     hazard.params = list(xvar = "time",
                          by = "hormon",
                          alpha = 0.05,
                          ylab = "Hazard"))

One continuous predictor with interaction

Now we fit a model with an interaction between a continuous variable, estrogen receptor (in fmol), and time.

mod_cb_tvc <- fitSmoothHazard(cens ~ estrec * ns(log(time), df = 3),
                              data = brcancer,
                              time = "time")
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(mod_cb_tvc)
#> 
#> Call:
#> glm(formula = formula, family = binomial, data = sampleData)
#> 
#> Deviance Residuals: 
#>     Min       1Q   Median       3Q      Max  
#> -0.1873  -0.1609  -0.1424  -0.1374   4.0452  
#> 
#> Coefficients:
#>                               Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)                   -85.0998    23.7005  -3.591  0.00033 ***
#> estrec                         -0.8162     0.4276  -1.909  0.05632 .  
#> ns(log(time), df = 3)1         50.9975    15.6089   3.267  0.00109 ** 
#> ns(log(time), df = 3)2        150.3241    46.0330   3.266  0.00109 ** 
#> ns(log(time), df = 3)3         30.3359     9.5193   3.187  0.00144 ** 
#> estrec:ns(log(time), df = 3)1   0.5565     0.2871   1.939  0.05256 .  
#> estrec:ns(log(time), df = 3)2   1.5452     0.8196   1.885  0.05939 .  
#> estrec:ns(log(time), df = 3)3   0.3461     0.1765   1.961  0.04991 *  
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3354.9  on 30198  degrees of freedom
#> Residual deviance: 3263.7  on 30191  degrees of freedom
#> AIC: 3279.7
#> 
#> Number of Fisher Scoring iterations: 13

There are now many ways to plot the time-varying effect of estrogen receptor on the hazard function. The default is to plot the 10th, 50th and 90th quantiles of the by variable:

# computed at the 10th, 50th and 90th quantiles of estrec
plot(mod_cb_tvc,
     hazard.params = list(xvar = "time",
                          by = "estrec",
                          alpha = 1,
                          ylab = "Hazard"))

We can also show the quartiles of estrec by specifying the breaks argument. If breaks is a single number, that will be the used as the number of breaks:

# computed at quartiles of estrec
plot(mod_cb_tvc,
     hazard.params = list(xvar = c("time"),
                          by = "estrec",
                          alpha = 1,
                          breaks = 4,
                          ylab = "Hazard"))

Alternatively, if breaks is a vector, it will be used as the actual values to be used:

# computed where I want
plot(mod_cb_tvc,
     hazard.params = list(xvar = c("time"),
                          by = "estrec",
                          alpha = 1,
                          breaks = c(3,2200),
                          ylab = "Hazard"))

Image and Perspective Plots

Instead of taking a cross-section of the effect of estrec on the hazard, we can plot a surface using the visreg2d function:

visreg2d(mod_cb_tvc,
         xvar = "time",
         yvar = "estrec",
         trans = exp,
         print.cond = TRUE,
         zlab = "Hazard",
         plot.type = "image")

visreg2d(mod_cb_tvc,
         xvar = "time",
         yvar = "estrec",
         trans = exp,
         print.cond = TRUE,
         zlab = "Hazard",
         plot.type = "persp")

# this can also work if 'rgl' is installed
# visreg2d(mod_cb_tvc, 
#          xvar = "time",
#          yvar = "estrec",
#          trans = exp,
#          print.cond = TRUE,
#          zlab = "Hazard",
#          plot.type = "rgl")

One continuous predictor with interaction and several other predictors

All the examples so far have only included two predictors in the regression equation. In this example, we fit a smooth hazard model with several predictors:

mod_cb_tvc <- fitSmoothHazard(cens ~ estrec * ns(log(time), df = 3) +
                                horTh +
                                age +
                                menostat +
                                tsize +
                                tgrade +
                                pnodes +
                                progrec,
                              data = brcancer,
                              time = "time")
#> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
summary(mod_cb_tvc)
#> 
#> Call:
#> glm(formula = formula, family = binomial, data = sampleData)
#> 
#> Deviance Residuals: 
#>     Min       1Q   Median       3Q      Max  
#> -0.6815  -0.1625  -0.1336  -0.0937   4.0734  
#> 
#> Coefficients:
#>                                 Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)                   -69.552989  18.124127  -3.838 0.000124 ***
#> estrec                         -0.474503   0.310324  -1.529 0.126250    
#> ns(log(time), df = 3)1         40.949772  11.921763   3.435 0.000593 ***
#> ns(log(time), df = 3)2        120.043222  35.307060   3.400 0.000674 ***
#> ns(log(time), df = 3)3         24.416030   7.202900   3.390 0.000700 ***
#> horThyes                       -0.344138   0.129997  -2.647 0.008115 ** 
#> age                            -0.010347   0.009235  -1.120 0.262576    
#> menostatPost                    0.256134   0.183651   1.395 0.163112    
#> tsize                           0.007918   0.003906   2.027 0.042643 *  
#> tgrade.L                        0.555963   0.191114   2.909 0.003625 ** 
#> tgrade.Q                       -0.221237   0.122604  -1.804 0.071156 .  
#> pnodes                          0.052212   0.007999   6.528 6.68e-11 ***
#> progrec                        -0.002300   0.000577  -3.986 6.71e-05 ***
#> estrec:ns(log(time), df = 3)1   0.327540   0.208656   1.570 0.116470    
#> estrec:ns(log(time), df = 3)2   0.896474   0.595469   1.505 0.132197    
#> estrec:ns(log(time), df = 3)3   0.202059   0.127073   1.590 0.111813    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3354.9  on 30198  degrees of freedom
#> Residual deviance: 3157.8  on 30183  degrees of freedom
#> AIC: 3189.8
#> 
#> Number of Fisher Scoring iterations: 13

In the following plot, we show the time-varying effect of estrec while controlling for all other variables. By default, the other terms in the model are set to their median if the term is numeric or the most common category if the term is a factor. The values of the other variables are shown in the output:

plot(mod_cb_tvc,
     hazard.params = list(xvar = "time",
                          by = "estrec",
                          alpha = 1,
                          breaks = 2,
                          ylab = "Hazard"))
#> Conditions used in construction of plot
#> estrec: 8 / 175
#> horTh: no
#> age: 53
#> menostat: Post
#> tsize: 25
#> tgrade: II
#> pnodes: 3
#> progrec: 51
#> offset: 0

#> $fit
#>      estrec time horTh age menostat tsize tgrade pnodes progrec offset cens
#>      visregFit visregLwr visregUpr
#>  [ reached 'max' / getOption("max.print") -- omitted 202 rows ]
#> 
#>  [ reached getOption("max.print") -- omitted 2 entries ]
#> attr(,"class")
#> [1] "visreg"

You can of course set the values of the other covariates as before, i.e. by specifying the cond argument as a named list to the hazard.params argument:

plot(mod_cb_tvc,
     hazard.params = list(xvar = "time",
                          by = "estrec",
                          cond = list(tgrade = "III", age = 49),
                          alpha = 1,
                          breaks = 2,
                          ylab = "Hazard"))
#> Conditions used in construction of plot
#> estrec: 8 / 175
#> horTh: no
#> age: 49
#> menostat: Post
#> tsize: 25
#> tgrade: III
#> pnodes: 3
#> progrec: 51
#> offset: 0

#> $fit
#>      estrec time horTh age menostat tsize tgrade pnodes progrec offset cens
#>      visregFit visregLwr visregUpr
#>  [ reached 'max' / getOption("max.print") -- omitted 202 rows ]
#> 
#>  [ reached getOption("max.print") -- omitted 2 entries ]
#> attr(,"class")
#> [1] "visreg"

Hazard Ratio

In this section we illustrate how to plot hazard ratios using the plot method for objects of class singleEventCB which is obtained from running the fitSmoothHazard function. Note that these function have only been thoroughly tested with family = "glm".

In what follows, the hazard ratio for a variable \(X\) is defined as

\[ \frac{h\left(t | X=x_1, \mathbf{Z}=\mathbf{z_1} ; \hat{\beta}\right)}{h(t | X=x_0, \mathbf{Z}=\mathbf{z_0} ; \hat{\beta})} \] where \(h(t|\cdot;\hat{\beta})\) is the hazard rate as a function of the variable \(t\) (which is usually time, but can be any other continuous variable), \(x_1\) is the value of \(X\) for the exposed group, \(x_0\) is the value of \(X\) for the unexposed group, \(\mathbf{Z}\) are other covariates in the model which are equal to \(\mathbf{z_1}\) in the exposed and \(\mathbf{z_0}\) in the unexposed group, and \(\hat{\beta}\) are the estimated regression coefficients.

As indicated by the formula above, it is most instructive to plot the hazard ratio as a function of a variable \(t\) only if there is an interaction between \(t\) and \(X\). Otherwise, the resulting plot will simply be a horizontal line across time.

Manson Trial (eprchd)

We use data from the Manson trial (NEJM 2003) which is included in the casebase package. This randomized clinical trial investigated the effect of estrogen plus progestin (estPro) on coronary heart disease (CHD) risk in 16,608 postmenopausal women who were 50 to 79 years of age at base line. Participants were randomly assigned to receive estPro or placebo. The primary efficacy outcome of the trial was CHD (nonfatal myocardial infarction or death due to CHD).

We fit a model with the interaction between time and treatment arm. We are therefore interested in visualizing the hazard ratio of the treatment over time.

data("eprchd")
eprchd <- transform(eprchd,
                    treatment = factor(treatment, levels = c("placebo","estPro")))
str(eprchd)
#> 'data.frame':    16608 obs. of  3 variables:
#>  $ time     : num  0.0833 0.0833 0.0833 0.0833 0.0833 ...
#>  $ status   : num  0 0 0 0 0 0 0 0 0 0 ...
#>  $ treatment: Factor w/ 2 levels "placebo","estPro": 1 1 1 1 1 1 1 1 1 1 ...

fit_mason <- fitSmoothHazard(status ~ treatment*time,
                             data = eprchd,
                             time = "time")
summary(fit_mason)
#> 
#> Call:
#> glm(formula = formula, family = binomial, data = sampleData)
#> 
#> Deviance Residuals: 
#>     Min       1Q   Median       3Q      Max  
#> -0.1655  -0.1489  -0.1466  -0.1312   3.1789  
#> 
#> Coefficients:
#>                      Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)          -6.08209    0.17532 -34.691  < 2e-16 ***
#> treatmentestPro       0.58160    0.22447   2.591  0.00957 ** 
#> time                  0.11026    0.04767   2.313  0.02073 *  
#> treatmentestPro:time -0.12161    0.06350  -1.915  0.05545 .  
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 3635.4  on 32723  degrees of freedom
#> Residual deviance: 3626.4  on 32720  degrees of freedom
#> AIC: 3634.4
#> 
#> Number of Fisher Scoring iterations: 7

To plot the hazard ratio, we must specify the newdata argument with a covariate pattern for the reference group. In this example, we treat the placebo as the reference group. Because we have fit an interaction with time, we also provide a sequence of times at which we would like to calculate the hazard ratio.

newtime <- quantile(fit_mason[["originalData"]][[fit_mason[["timeVar"]]]],
                    probs = seq(0.01, 0.99, 0.01))

# reference category
newdata <- data.frame(treatment = factor("placebo",
                                         levels = c("placebo", "estPro")),
                      time = newtime)
str(newdata)
#> 'data.frame':    99 obs. of  2 variables:
#>  $ treatment: Factor w/ 2 levels "placebo","estPro": 1 1 1 1 1 1 1 1 1 1 ...
#>  $ time     : num  0.917 1.75 2.5 3.167 3.417 ...

plot(fit_mason,
     type = "hr",
     newdata = newdata,
     var = "treatment",
     increment = 1,
     xvar = "time",
     ci = T,
     rug = T)

In the call to plot we specify the xvar which is the variable plotted on the x-axis, the var argument which specified the variable for which we want the hazard ratio. The increment = 1 indicates that we want to increment var by 1 level, which in this case is estPro. Alternatively, we can specify the exposed argument which should be a function that takes newdata and returns the exposed dataset. The following call is equivalent to the one above:

plot(fit_mason,
     type = "hr",
     newdata = newdata,
     exposed = function(data) transform(data, treatment = "estPro"),
     xvar = "time",
     ci = T,
     rug = T)

Alternatively, if we want the placebo group to be the exposed group, we can change the newdata argument to the following:

newdata <- data.frame(treatment = factor("estPro",
                                         levels = c("placebo", "estPro")),
                      time = newtime)
str(newdata)
#> 'data.frame':    99 obs. of  2 variables:
#>  $ treatment: Factor w/ 2 levels "placebo","estPro": 2 2 2 2 2 2 2 2 2 2 ...
#>  $ time     : num  0.917 1.75 2.5 3.167 3.417 ...

levels(newdata$treatment)
#> [1] "placebo" "estPro"

Note that the reference category in newdata is still placebo. Therefore we must set increment = -1 in order to get the exposed dataset:

plot(fit_mason,
     type = "hr",
     newdata = newdata,
     var = "treatment",
     increment = -1,
     xvar = "time",
     ci = TRUE,
     rug = TRUE)

If the \(X\) variable has more than two levels, than, increment works the same way, e.g. increment = 2 will provide an exposed group two levels above the value in newdata.

Save results

In order to save the data used to make the plot, you simply have to assign the call to plot to a variable. This is particularly useful if you want to really customize the plot aesthetics:

result <- plot(fit_mason,
               type = "hr",
               newdata = newdata,
               var = "treatment",
               increment = -1,
               xvar = "time",
               ci = TRUE,
               rug = TRUE)

head(result)
#>    treatment      time log_hazard_ratio standarderror hazard_ratio lowerbound
#> 1%    estPro 0.9166667       -0.4701248     0.1766524    0.6249242  0.4420390
#> 2%    estPro 1.7500000       -0.3687804     0.1401767    0.6915773  0.5254387
#> 3%    estPro 2.5000000       -0.2775704     0.1184746    0.7576223  0.6006299
#> 4%    estPro 3.1666667       -0.1964948     0.1133770    0.8216056  0.6578952
#> 5%    estPro 3.4166667       -0.1660915     0.1154775    0.8469688  0.6754182
#> 6%    estPro 3.9166667       -0.1052848     0.1257313    0.9000682  0.7034816
#>    upperbound
#> 1%  0.8834748
#> 2%  0.9102472
#> 3%  0.9556492
#> 4%  1.0260536
#> 5%  1.0620917
#> 6%  1.1515905

Session information