使用 rms 包中的 bplot 函数绘制等高线图

Contour plot using bplot function in rms package

我一直在尝试根据 "rms" 包中的 bplot 函数用 R 为预测模型绘制等高线图。代码如下:

library(rms)
n <- 1000
set.seed(17)
age <- rnorm(n, 50, 10)
blood.pressure <- rnorm(n, 120, 15)
cholesterol <- rnorm(n, 200, 25)
sex <- factor(sample(c('female','male'), n,TRUE))
L <- .4*(sex=='male') + .045*(age-50) + (log(cholesterol - 10)-5.2)*(-2*(sex=='female') + 2*(sex=='male'))
y <- ifelse(runif(n) < plogis(L), 1, 0)
ddist <- datadist(age, blood.pressure, cholesterol, sex)
options(datadist='ddist')
fit <- lrm(y ~ blood.pressure + sex * (age + rcs(cholesterol,4)), x=TRUE, y=TRUE)
p <- Predict(fit, age, cholesterol, sex, np=50)
bplot(p,, contourplot, region = TRUE,col.regions=topo.colors)

而且我注意到输出图是这样的:

我找不到如何平滑两个填充区域之间的锯齿形边界线,所以我想知道是否可以使用 ggplot2 制作这种用于预测模型的等高线图,或者是否有任何其他解决方案来平滑锯齿形边界线。

您可以使用 geom_tilegeom_contour 的组合绘制类似的图。

library(ggplot2)
ggplot(data.frame(p), aes(age, cholesterol, fill = yhat, z = yhat)) +
    geom_tile() +
    geom_contour(color = "black") +
    scale_fill_distiller(palette = "Spectral", limits = c(-2, 2)) +
    labs(x = "Age",
         y = expression(Total~Cholesterol["mg/dl"]),
         fill = NULL) +
    facet_grid(~ sex) +
    theme_classic()

编辑:根据 OP 的要求,我添加了离散颜色:

ggplot(data.frame(p), aes(age, cholesterol, z = yhat)) +
    geom_tile(aes(fill = factor(round(yhat)))) +
    geom_contour(color = "black") +
    labs(x = "Age",
         y = expression(Total~Cholesterol["mg/dl"]),
         fill = NULL) +
    facet_grid(~ sex) +
    theme_classic()