# Load necessary libraries
library(ggplot2)
library(reshape2)
# Define a reusable function
<- function(data, title = "Correlation Matrix Heatmap") {
plot_correlation_matrix # Step 1: Filter numeric columns
<- data[sapply(data, is.numeric)]
numeric_data
# Step 2: Calculate the correlation matrix
<- cor(numeric_data, use = "complete.obs")
cor_matrix
# Step 3: Melt the matrix into long format
<- melt(cor_matrix, varnames = c("Variable1", "Variable2"), value.name = "Correlation")
cor_df
# Step 4: Create the heatmap
ggplot(cor_df, aes(x = Variable1, y = Variable2, fill = Correlation)) +
geom_tile(color = "white") +
geom_text(aes(label = round(Correlation, 2)), color = "black", size = 3.5) +
scale_fill_gradient2(
low = "blue",
high = "red",
mid = "white",
midpoint = 0,
limit = c(-1, 1),
name = "Correlation"
+
) theme_minimal(base_size = 12) +
coord_fixed() +
labs(
title = title,
x = NULL,
y = NULL
+
) theme(
axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1),
panel.grid = element_blank()
)
}
# Example usage with the built-in mtcars dataset
plot_correlation_matrix(mtcars)
Program 14
Program 14
Develop a R program to calculate and visualize a correlation matrix for a given dataset, with color coded cells indicating the strength and direction of correlation , using ggplot2 geom_time function .