I am using the rms package to perform Cox regression with age as restricted cubic splines with 4 knots, see reproducible code below from the rms package documentation. My problem is: How do I change the y axis interval for the ggplot-output? I tried adding scale_y_continuous(limits = c(0,20)) but it didn't alter the axis
library(ggplot)
library(rms)
# NOT RUN {
# Simulate data from a population model in which the log hazard
# function is linear in age and there is no age x sex interaction
n <- 1000
set.seed(731)
age <- 50 12*rnorm(n)
label(age) <- "Age"
sex <- factor(sample(c('Male','Female'), n,
rep=TRUE, prob=c(.6, .4)))
cens <- 15*runif(n)
h <- .02*exp(.04*(age-50) .8*(sex=='Female'))
dt <- -log(runif(n))/h
label(dt) <- 'Follow-up Time'
e <- ifelse(dt <= cens,1,0)
dt <- pmin(dt, cens)
units(dt) <- "Year"
dd <- datadist(age, sex)
options(datadist='dd')
S <- Surv(dt,e)
f <- cph(S ~ rcs(age,4) sex, x=TRUE, y=TRUE)
cox.zph(f, "rank") # tests of PH
anova(f)
ggplot(Predict(f, age, sex, fun=exp)) # plot age effect, 2 curves for 2 sexes
scale_y_continuous(limits = c(0,20))
CodePudding user response:
Unusually, the Predict
class of rms
has its own S3 method for ggplot
, which automatically adds position scales, coordinates and geom layers. This makes it easier to plot Predict
objects, but limits extensibility. In particular, it already sets the y limits via a CoordCartesian
, which over-rides any y axis scales you add.
The simplest way round this is to add a new coord_cartesian
which will over-ride the existing Coord
object (though also generate a message).
ggplot(Predict(f, age, sex, fun=exp)) # plot age effect, 2 curves for 2 sexes
coord_cartesian(ylim = c(0, 20))
#> Coordinate system already present. Adding new coordinate system,
#> which will replace the existing one.
The alternative is to store the plot and change its coord limits, which doesn't generate a message but is a bit "hacky"
p <- ggplot(Predict(f, age, sex, fun=exp))
p$coordinates$limits$y <- c(0, 20)
p
You can also change the y axis limits to NULL
in the above code, which will allow your axis limits to be set using scale_y_continuous
instead.