I have been trying to make a contour plot for prediction models with R, based on the bplot function in "rms" package. The codes are as follows:
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)
And I noticed that the output figure was like this:
I couldn't find out how to smoothen the zigzag borderlines between two filled regions, so I wonder if this kind of contour plot for prediction models could be made with ggplot2 or if there are any other solutions to smoothen the zigzag borderlines.
You can plot similar plot with combination of geom_tile
and geom_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()
Edit: As OP requested I added discrete colors:
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()