我正在使用 rms 包執行 Cox 回歸,將年齡作為 4 節的受限三次樣條曲線,請參閱下面 rms 包檔案中的可重現代碼。我的問題是:如何更改 ggplot 輸出的 y 軸間隔?我嘗試添加 scale_y_continuous(limits = c(0,20)) 但它沒有改變軸
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))
uj5u.com熱心網友回復:
不同尋常的是, 的Predict類rms有自己的 S3 方法ggplot,它會自動添加位置比例、坐標和幾何圖層。這使得繪制Predict物件更容易,但限制了可擴展性。特別是,它已經通過 a 設定了 y 限制CoordCartesian,它覆寫了您添加的任何 y 軸刻度。
解決此問題的最簡單方法是添加一個新物件coord_cartesian,它將覆寫現有Coord物件(盡管也會生成一條訊息)。
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.

另一種方法是存盤情節并更改其坐標限制,這不會生成訊息但有點“hacky”
p <- ggplot(Predict(f, age, sex, fun=exp))
p$coordinates$limits$y <- c(0, 20)
p

您還可以在上面的代碼中將 y 軸限制更改為NULL,這將允許您設定軸限制scale_y_continuous。
uj5u.com熱心網友回復:
雖然有點費力,但您始終可以通過將物件轉換為第一原理來根據第一原理創建情節data.frame。這種方式的好處是您可以完全控制要添加的內容。
age_data <- as.data.frame(Predict(f, age, sex, fun = exp))
ggplot(age_data, aes(x = age, y = yhat, colour = sex))
geom_line()
geom_ribbon(aes(ymin = lower, ymax = upper), alpha = 0.2)
scale_y_continuous(limits = c(0, 20))

不過,@Allans 方法對于您的特定要求要簡單得多!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462739.html
