How to create faceted correlation plot using GGPLOT

前端 未结 3 1999
失恋的感觉
失恋的感觉 2021-02-10 06:07

I have a data frame created the following way.

library(ggplot2)

x <- data.frame(letters[1:10],abs(rnorm(10)),abs(rnorm(10)),type=\"x\")
y <- data.frame(le         


        
3条回答
  •  猫巷女王i
    2021-02-10 06:35

    Since your data is not in the appropriate format, some reshaping is necessary before it can be plotted.

    Firstly, reshape the data to the long format:

    library(reshape2)
    allM <- melt(all[-1], id.vars = "type")
    

    Split the values along type and val1 vs. val2:

    allList <- split(allM$value, interaction(allM$type, allM$variable))
    

    Create a list of all combinations:

    allComb <- unlist(lapply(c(1, 3), 
                      function(x)
                        lapply(c(2 ,4), 
                               function(y) 
                                 do.call(cbind, allList[c(x, y)]))), 
               recursive = FALSE)
    

    Create a new dataset:

    allNew <- do.call(rbind, 
                      lapply(allComb, function(x) {
                                        tmp <- as.data.frame(x)
                                        tmp <- (within(tmp, {xval <- names(tmp)[1]; 
                                                             yval <- names(tmp)[2]}))
                                        names(tmp)[1:2] <- c("x", "y")
                                        tmp}))
    

    Plot:

    library(ggplot2)
    p <- ggplot(allNew, aes(x = x, y = y)) + 
           geom_smooth(method = "lm")  + 
           geom_point() +
           facet_grid(yval ~ xval) 
    # Calculate correlation for each group
    library(plyr)
    cors <- ddply(allNew, .(yval, xval), summarise, cor = round(cor(x, y), 2))
    p + geom_text(data=cors, aes(label=paste("r=", cor, sep="")), x=0.5, y=0.5)
    

    enter image description here

提交回复
热议问题