Creating heat maps from correlations between two dataframes

I have two dataframes, one with some sensory data, and some with some analytical data. I want to see if there are any correlations between any of the analytical data and the sensory data, so basically a correlation matrix across all values in each dataframe. But then I want to be able to plot these as a heatmap.

I used the cor function:


cordata2<-cor(x=sensory, y=analytical,method="pearson")

and this gave me a matrix. But then I'm having trouble formatting a geom_tile plot with aesthetics from here, getting the error:

> ggplot(cordata2, aes(x=sensory,y=analytical))+
+   geom_tile()
Error in `fortify()`:
! `data` must be a <data.frame>, or an object coercible by `fortify()`, not a
  double matrix.
Run `rlang::last_trace()` to see where the error occurred.

I'm not sure how to fix this. If anyone could advise, that would be great.

The cor function returns a matrix and ggplot() needs a data.frame. Here is an example with some toy data. I also included a plot made with the corrplot package, which you may find useful. There are many options for plotting in corrplot.
Notice the order of the y axis is different in the two plots.

DF1 <- data.frame(X1 = rnorm(20), X2 = rnorm(20), X3 = rnorm(20))
DF2 <- data.frame(Y1 = rnorm(20), Y2 = rnorm(20), Y3 = rnorm(20))
cordata2 <- cor(DF1,DF2)
class(cordata2)
#> [1] "matrix" "array"
cordata2
#>            Y1          Y2          Y3
#> X1  0.1755019 -0.34933248  0.03584859
#> X2 -0.1747748 -0.17497220 -0.18751314
#> X3  0.0640173 -0.08169084 -0.07844367
library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.3.3

DF3 <- as_tibble(cordata2, rownames = "Xvar")
DF3
#> # A tibble: 3 × 4
#>   Xvar       Y1      Y2      Y3
#>   <chr>   <dbl>   <dbl>   <dbl>
#> 1 X1     0.176  -0.349   0.0358
#> 2 X2    -0.175  -0.175  -0.188 
#> 3 X3     0.0640 -0.0817 -0.0784

DF3long <- pivot_longer(DF3, cols = Y1:Y3, names_to = "Yvar")
DF3long
#> # A tibble: 9 × 3
#>   Xvar  Yvar    value
#>   <chr> <chr>   <dbl>
#> 1 X1    Y1     0.176 
#> 2 X1    Y2    -0.349 
#> 3 X1    Y3     0.0358
#> 4 X2    Y1    -0.175 
#> 5 X2    Y2    -0.175 
#> 6 X2    Y3    -0.188 
#> 7 X3    Y1     0.0640
#> 8 X3    Y2    -0.0817
#> 9 X3    Y3    -0.0784
ggplot(DF3long, aes(x=Yvar,y=Xvar, fill = value))+
     geom_tile()


library(corrplot)
#> corrplot 0.92 loaded
corrplot(cordata2)

Created on 2024-08-02 with reprex v2.0.2

You might also want to take a look at GGally::ggcorr()

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.