ggpairs plot with heatmap of correlation values

前端 未结 2 1404
花落未央
花落未央 2020-12-06 11:33

My question is twofold;

I have a ggpairs plot with the default upper = list(continuous = cor) and I would like to colour the tiles by correlation values

2条回答
  •  遥遥无期
    2020-12-06 12:16

    You can map a background colour to the cell by writing a quick custom function that can be passed directly to ggpairs. This involves calculating the correlation between the pairs of variables, and then matching to some user specified colour range.

    my_fn <- function(data, mapping, method="p", use="pairwise", ...){
    
                  # grab data
                  x <- eval_data_col(data, mapping$x)
                  y <- eval_data_col(data, mapping$y)
    
                  # calculate correlation
                  corr <- cor(x, y, method=method, use=use)
    
                  # calculate colour based on correlation value
                  # Here I have set a correlation of minus one to blue, 
                  # zero to white, and one to red 
                  # Change this to suit: possibly extend to add as an argument of `my_fn`
                  colFn <- colorRampPalette(c("blue", "white", "red"), interpolate ='spline')
                  fill <- colFn(100)[findInterval(corr, seq(-1, 1, length=100))]
    
                  ggally_cor(data = data, mapping = mapping, ...) + 
                    theme_void() +
                    theme(panel.background = element_rect(fill=fill))
                }
    

    Using the data in Marco's answer:

    library(GGally)    # version: ‘1.4.0’
    
    p1 <- ggpairs(sample_df, 
                       upper = list(continuous = my_fn),
                       lower = list(continuous = "smooth"))  
    

    Which gives:


    A followup question Change axis labels of a modified ggpairs plot (heatmap of correlation) noted that post plot updating of the theme resulted in the panel.background colours being removed. This can be fixed by removing the theme_void and removing the grid lines within the theme. i.e. change the relevant bit to (NOTE that this fix is not required for ggplot2 v3.3.0)

    ggally_cor(data = data, mapping = mapping, ...) + 
               theme(panel.background = element_rect(fill=fill, colour=NA),
                     panel.grid.major = element_blank()) 
    

提交回复
热议问题