简体   繁体   中英

How to visualize logistic regression by heatmap in R

I have logistic regression with binary observations y (0,1) and two independent variables (x1 and x2). I want to visualize model predictions by heatmap (matrix of predicted values in 2D). I am able to partially get what I want (see plot below), but how to add:

  • colour scale to predicted values
  • appropriate axes (horizontal and vertical) for x1 and x2
  • how do I know the appropriate rotation of matrix? Is x1 (or x2) on horizontal or vertical axis?

...

# data simulation
set.seed(16)
x_sample.lr <- seq(1,100, by = 0.5)
# data.frame creation
lr.df <- data.frame(y = sample(c(0,1), 50, replace = TRUE),
                    x1 = sample(x_sample.lr, 50, replace = TRUE),
                    x2 = sample(x_sample.lr, 50, replace = TRUE))

# model creation
lr.mod <- glm(y ~ x1*x2, data = lr.df, family = "binomial")
anova(lr.mod, test = "Chi")
summary(lr.mod)

# ...calculating prediction
lr.pred <- expand.grid(x1 = x_sample.lr, x2 = x_sample.lr)
lr.pred$predicted <- predict(lr.mod, newdata = lr.pred)
head(lr.pred)
#    x1 x2 predicted
# 1 1.0  1  2.306825
# 2 1.5  1  2.279347
# 3 2.0  1  2.251869

# ...plot visualization
pl.pred.mtrx <- matrix(lr.pred$predicted, ncol = sqrt(nrow(lr.pred)))
image(pl.pred.mtrx)

在此处输入图像描述

when you use matrix(), it fills in the matrix by column, so checking your first 199 values, all with x2 == 1,

all(lr.pred$predicted[1:199] == pl.pred.mtrx[,1])

When you plot this matrix with image(), you actually transpose the matrix and plot the colours, you can try with this:

image(matrix(1:18,ncol=2))

So in your plot, the xaxis is x1 and yaxis is x2, and we can add the axis labels, suppress ticks.

# we place it at 1,10,20..100
TICKS = c(1,10*(1:10))

image(pl.pred.mtrx,xlab="x1",ylab="x2",xaxt="n",yaxt="n")
# position of your ticks is the num over the length
axis(side = 1, at = which(x_sample.lr %in% TICKS)/nrow(pl.pred.mtrx),labels = TICKS)
axis(side = 2, at = which(x_sample.lr %in% TICKS)/ncol(pl.pred.mtrx),labels = TICKS)

在此处输入图像描述

I don't know an easy way to add the color legend. So my suggestion is to use fields:

library(fields)
# in this case we know how x and y will run.. with respect to matrix z
# in other situations, this will depend on how you construct z
DA = list(x=x_sample.lr,y=x_sample.lr,z=pl.pred.mtrx)
image.plot(DA,col=hcl.colors(12, "YlOrRd", rev = TRUE))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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