rm(list=ls())
library(ggplot2)
library(dplyr)

######################
cor_df <- read.csv("./data.csv") %>%
  mutate(
    significance = case_when(
      p_value < 0.001 ~ "**",
      p_value < 0.05 ~ "*",
      TRUE ~ ""
    ),
    
    text_color = ifelse(abs(Correlation) > 0.6, "white", "black")  
  )

color_palette <- colorRampPalette(c("#053061", "#2166AC", "#F7F7F7", "#B2182B", "#67001F"))(100)
cor_range <- range(cor_df$Correlation, na.rm = TRUE)
mid_value <- (cor_range[1] + cor_range[2])/2
plot <- ggplot(cor_df, aes(x = Var1, y = Var2, fill = Correlation)) +
  geom_tile(color = "white", linewidth = 0.3, na.rm = TRUE) +
  geom_text(aes(label = sprintf("%.2f%s", Correlation, significance), 
                color = text_color),
            size = 4.2, 
            fontface = "bold",
            show.legend = FALSE) +
  scale_fill_gradientn(
    colors = color_palette,
    values = scales::rescale(seq(cor_range[1], cor_range[2], length.out = 100)),
    limits = c(cor_range[1], cor_range[2]),
    na.value = "grey90",
    guide = guide_colorbar(
      title = "OR",
      title.position = "top",
      title.theme = element_text(size = 14, face = "bold"),
      barwidth = unit(1.2, "cm"),
      barheight = unit(12, "cm"),
      frame.colour = "black",
      ticks.colour = "black",
      label.theme = element_text(size = 15)
    )
  ) +
  scale_color_identity() +
  theme_minimal(base_size = 14) +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, face = "bold"),
    axis.text.y = element_text(face = "bold"),
    axis.title = element_text(size = 16, face = "bold"),
    panel.grid = element_blank(),
    legend.position = "right",
    plot.title = element_text(hjust = 0.8, size = 18, face = "bold"),
    plot.margin = margin(1, 1, 1, 1, "cm")
  ) +
  labs(
    x = "Gut Microbiota Taxonomy",
    y = "MR Analysis Methods",
    title = "Causal Relationship Between Gut Microbiota and COPD"
  ) +
  coord_fixed(ratio = 0.8)
ggsave("Correlation_Heatmap.pdf", plot,limitsize = FALSE, 
       width = 20, height = 15, units = "in", dpi = 300)
