Program15

Author

Ashutosh

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 .

# Load necessary libraries
library(ggplot2)
library(reshape2)

# Define a reusable function
plot_correlation_matrix <- function(data, title = "Correlation Matrix Heatmap") {
  # Step 1: Filter numeric columns
  numeric_data <- data[sapply(data, is.numeric)]
  
  # Step 2: Calculate the correlation matrix
  cor_matrix <- cor(numeric_data, use = "complete.obs")
  
  # Step 3: Melt the matrix into long format
  cor_df <- melt(cor_matrix, varnames = c("Variable1", "Variable2"), value.name = "Correlation")
  
  # 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)