繁体   English   中英

在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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM