# 设置工作环境
rm(list = ls())
setwd("D:/马明福/新文章/原始图/IHCscore")

# 加载必要的包
library(ggplot2)
library(ggsignif)
library(reshape2) # 因为使用了melt函数

# 加载数据
df <- read.table("IHCscoreUBE2S.txt", header = T, check.names = F)
# 转换数据
data <- melt(df)
data$G <- rep(c("N", "T"), each = 15)

# 自定义函数来格式化 p 值
format_p_value <- function(p) {
  if (p < 0.001) {
    return("p < 0.001")
  } else {
    return(paste0("p = ", round(p, 3)))
  }
}

# 进行 t 检验并获取 p 值
t_test_result <- t.test(value ~ G, data = data)
p_value <- t_test_result$p.value

# 基础绘图
p1 <- ggplot(data, aes(G, value)) +
  # 绘制条形图，设置宽度参数
  geom_bar(aes(fill = G), color = 'grey50', stat = "summary",
           fun = mean, position = "dodge", size = 0.8, width = 0.6) + 
  # 误差棒
  stat_summary(fun.data ='mean_sd', geom = "errorbar", width = 0.2, size = 0.8) +
  # 设置 x 轴和 y 轴标签
  labs(x = NULL, y = "IHC score of UBE2S") +
  # 颜色
  scale_fill_manual(values = c("#ADD8E6", "#F4A460")) +
  # 显著性，显示具体 p 值
  geom_signif(comparisons = list(c("N", "T")),
              map_signif_level = format_p_value, 
              test = "t.test",
              # 增大星号大小
              textsize = 12,face = "bold", 
              y_position = 8.5,
              # 设置tip_length为0，去除两端的竖线
              tip_length = 0.03, 
              # 设置lineheight为0，去除中间的横线
              lineheight = 1, 
              vjust = -0.5,
              # 加深星号颜色
              size = 0.8, color = "black", alpha = 1) + 
  scale_y_continuous(expand = c(0, 0), limits = c(0, 10.5), breaks = c(0, 2, 4, 6, 8, 10)) +
  # 修改 x 轴刻度标签
  scale_x_discrete(labels = c("N" = "Normal", "T" = "Cancer")) +
  # 主题相关设置
  theme_classic() +
  theme(axis.text = element_text(size = 28,face = "bold"),
        legend.position = "none",
        axis.line = element_line(size = 0.8),
        # 增大 y 轴标签字体大小
        axis.title.y = element_text(size = 30,face = "bold")) 

# 显示图形
print(p1)

# 保存图形
ggsave("IHCUBE2S.png", plot = p1, width = 5, height = 6, dpi = 300)