library(readxl)
library(ggplot2)
library(reshape2)
library(ggpubr)

# 设置工作目录到包含Excel文件的路径
setwd("C:/Users/PC/Desktop/Auto/AI病理挑战杯美图/ResNet-18")

# 读取Excel文件
data <- read_excel("Data.xlsx")

# 假设诊断结果是以字符串形式存储的，将它们转换为数值型
data_selected <- data[, c("人工1", "人工2", "人工3", "AI结果", "联合人工1", "联合人工2", "联合人工3")]
data_selected <- as.data.frame(lapply(data_selected, function(x) as.numeric(as.character(x))))

# 确保没有NA值，如果有，需要处理它们
data_selected <- na.omit(data_selected)

# 计算相关系数矩阵
cor_matrix <- cor(data_selected, use = "pairwise.complete.obs")

# 将相关系数矩阵转换为长格式，以便绘制热图
cor_melted <- melt(cor_matrix)

# 创建热图
p <- ggplot(data = cor_melted, aes(Var1, Var2, fill = value)) +
  geom_tile(color = "white") +
  scale_fill_gradient2(low = "blue", high = "red", mid = "white",
                       midpoint = 0, limit = c(-1,1), space = "Lab", 
                       name="Pearson\nCorrelation") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, vjust = 1, size = 12, hjust = 1),
        axis.text.y = element_text(size = 12)) +
  coord_fixed() +
  ggtitle("Correlation Heatmap of Diagnoses") +
  xlab("Diagnosis") + 
  ylab("Diagnosis") +
  # 修改轴标签为英文
  scale_x_discrete(labels = c("Human 1", "Human 2", "Human 3", "AI Result", 
                              "Combined Human 1", "Combined Human 2", "Combined Human 3")) +
  scale_y_discrete(labels = c("Human 1", "Human 2", "Human 3", "AI Result", 
                              "Combined Human 1", "Combined Human 2", "Combined Human 3"))

# 保存300dpi的PNG图片
ggsave("Correlation_Heatmap.png", plot = p, width = 10, height = 8, dpi = 300)
