How to make customized correlation plot?

50 Views Asked by At

I have dataframe with 6 columns ab1, ab2, ab3, ab4, ab5, ab6. In the above example, I need only plot of correlation between ab1 to ab2, ab1 to ab3, ab1 to ab4, ab1 to ab5, ab1 to ab6 I dont want to plot ab2 to ab3, ab2 to ab4 and remaining.....

The final plot will have 2*6 heatmap. How do I do this in R?

# Sample data
set.seed(123)
df <- data.frame(ab1 = rnorm(100),
                 ab2 = rnorm(100),
                 ab3 = rnorm(100),
                 ab4 = rnorm(100),
                 ab5 = rnorm(100),
                 ab6 = rnorm(100))

# Calculate correlations
cor_matrix <- cor(df)
1

There are 1 best solutions below

0
On BEST ANSWER

You can just manipulate the correlation object and select the appropriate columns:

set.seed(123)
df <- data.frame(ab1 = rnorm(100),
                 ab2 = rnorm(100),
                 ab3 = rnorm(100),
                 ab4 = rnorm(100),
                 ab5 = rnorm(100),
                 ab6 = rnorm(100))

# Calculate correlations
cor_matrix <- cor(df)

# Just select correlation between ab1 and rest of rows
data.frame(ab1 = cor_matrix[2:6, 1]) |> 
  as.matrix() |> 
  corrplot::corrplot()

Created on 2023-12-13 with reprex v2.0.2