Last active
August 29, 2015 14:23
-
-
Save euclidjda/988e428967db40024462 to your computer and use it in GitHub Desktop.
2D contour heatmaps for illustrating factor relationships in machine learning
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
| require(mlbench) | |
| require(rgl) | |
| require(MASS) | |
| require(plot3D) | |
| ##' diverging colour palette function with set midpoint | |
| ##' | |
| ##' returns a palette function that maps values to colours, with | |
| ##' a midpoint (defaulting to 0) corresponding to the central colour | |
| ##' @title diverging_palette | |
| ##' @export | |
| ##' @param d data giving the range of the palette | |
| ##' @param centered logical, whether to use both sides from the midpoint symmetrically | |
| ##' @param midpoint numeric value corresponding to the central colour | |
| ##' @param colors vector of colors, length must be odd | |
| ##' @return a function | |
| ##' @author baptiste Auguie | |
| ##' @family low_level | |
| ##' @examples | |
| ##' grid.raster(diverging_palette(1:10, TRUE, mid=2, col=c("blue", "white", "red"))(1:10)) | |
| diverging_palette <- function(d = NULL, centered = FALSE, midpoint = 0, | |
| colors = RColorBrewer::brewer.pal(7,"PRGn")){ | |
| half <- length(colors)/2 | |
| if(!length(colors)%%2) | |
| stop("requires odd number of colors") | |
| if( !centered && !(midpoint <= max(d, na.rm=TRUE) && midpoint >= min(d, na.rm=TRUE))) | |
| warning("Midpoint is outside the data range!") | |
| values <- if(!centered) { | |
| low <- seq(min(d, na.rm=TRUE), midpoint, length=half) | |
| high <- seq(midpoint, max(d, na.rm=TRUE), length=half) | |
| c(low[-length(low)], midpoint, high[-1]) | |
| } else { | |
| mabs <- max(abs(d - midpoint), na.rm=TRUE) | |
| seq(midpoint-mabs, midpoint + mabs, length=length(colors)) | |
| } | |
| scales::gradient_n_pal(colors, values = values) | |
| } | |
| data(PimaIndiansDiabetes) | |
| data_p <- subset(PimaIndiansDiabetes,diabetes=='pos') | |
| data_n <- subset(PimaIndiansDiabetes,diabetes=='neg') | |
| kde_p <- kde2d(data_p$glucose,data_p$mass,n=500) | |
| kde_n <- kde2d(data_n$glucose,data_n$mass,n=500) | |
| z <- kde_p$z - kde_n$z | |
| colors <- diverging_palette( d=z, | |
| colors=RColorBrewer::brewer.pal(11,"Spectral") )(seq(min(z),max(z),(max(z)-min(z))/10)) | |
| image2D(x = kde_p$x, y = kde_p$y, z, | |
| col = colors, | |
| xlab="glucose",ylab="mass", | |
| shade = 0.2, rasterImage = TRUE, | |
| contour = list(col = "white", labcex = 0.8, lwd = 1, alpha = 0.5)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment