Last active
July 18, 2026 20:10
-
-
Save jonesor/cc58f21902857bf129eb7f4fc3afe57c to your computer and use it in GitHub Desktop.
Make a contour plot with a heat map.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Packages | |
| library(ggplot2) | |
| # Read in some data for the example | |
| # The data are grade data and acceptance into grad school. | |
| # GRE (Graduate Record Exam scores), GPA (grade point average) | |
| mydata <- read.csv("https://stats.oarc.ucla.edu/stat/data/binary.csv") | |
| head(mydata) | |
| summary(mydata) | |
| mylogit <- glm(admit ~ gre + gpa + gre:gpa, data = mydata, family = "binomial") | |
| summary(mylogit) | |
| # Use expand.grid to create a "grid" of data to predict from | |
| # The grid takes all possible values based on the original data | |
| newdat <- expand.grid(gre = seq(220, 800, 1), gpa = seq(2.2, 4, 0.01)) | |
| # Predict from the model, and place values within the "newdat" object. | |
| newdat$pv <- predict(mylogit, newdata = newdat, type = "response") | |
| # Basic (empty) plot | |
| A <- ggplot(data = newdat, aes(x = gre, y = gpa, z = pv)) | |
| # Plot (blue with white contours) | |
| A + geom_raster(aes(fill = pv)) + | |
| geom_contour(colour = "white", bins = 5) | |
| # A different colour | |
| A + geom_raster(aes(fill = pv)) + | |
| scale_fill_viridis_c(option = "magma") | |
| # Make a plot with a contour line at a particular point | |
| A + geom_raster(aes(fill = pv)) + | |
| scale_fill_viridis_c(option = "viridis") + | |
| geom_contour(colour = "white", breaks = c(.4)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment