r - Adding a third dimension on a 2D heatmap -
i wondering if me out following question:
i have correlation matrix , third variable (continuous) every possible pair in correlation matrix.
here toy example:
set.seed(1234) x <- rnorm(1000,2,1) y <- 0.1*x+rnorm(1000,1,1) z <- y+rnorm(1000) third.dimension <- c("(x,y)" = 0.3, "(x,z)" = 0.5, "(y,z)"= 1) my.df <- data.frame(x,y,z)
first, want create heatmap of correlation matrix with
heatmap(cor(my.df))
next, have coloured dot within each "cell" of heatmap, depending on value of third dimension respective pair. example - if value between 0 , 0.49, have black dot, if between 0.5 , 1, grey dot etc.
hence, have correlation between z , y, say, have grey dot painted in corresponding "cell" of correlation matrix.
thanks in advance help!
this should work you:
set.seed(1234) x <- rnorm(1000,2,1) y <- 0.1*x+rnorm(1000,1,1) z <- y+rnorm(1000) third.dimension <- c("(x,y)" = 0.3, "(x,z)" = 0.5, "(y,z)"= 1) my.df <- data.frame(x,y,z) # required function val2col <- function(z, zlim, col = heat.colors(12), breaks){ if(!missing(breaks)){ if(length(breaks) != (length(col)+1)){stop("must have 1 more break color")} } if(missing(breaks) & !missing(zlim)){ breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) } if(missing(breaks) & missing(zlim)){ zlim <- range(z, na.rm=true) breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) } cut <- cut(z, breaks=breaks, include.lowest = true) colorlevels <- col[match(cut, levels(cut))] # assign colors heights each point return(colorlevels) } # plot cor <- list( x = seq(ncol(my.df)), y = seq(ncol(my.df)), z = cor(my.df) ) image(cor, xaxt="n", yaxt="n") axis(1, at=cor$x, labels = names(my.df)) axis(2, at=cor$x, labels = names(my.df)) box() cor$col <- val2col(c(cor$z), col = grey.colors(21), zlim=c(0,1)) points(expand.grid(x=cor$x, y=cor$y), col=cor$col, pch=16, cex=3)
Comments
Post a Comment