# 数据准备

data <- c(rnorm(200))
name <- c(rep("control", 99),rep("treat",101))
res <- data.frame(data,name)


# 箱线图美化

## 01 一个平平无奇的箱线图

library(ggplot2)
g <- ggplot(res, aes(name, data))+geom_boxplot(aes(fill = name ))


## 02 给箱线图加上误差线

library(ggsignif)
compared_list = list(c("control", "treat"))  #设定比较组
g + geom_signif(comparisons = compared_list, test = t.test, step_increase = 0.2)


map_signif_level=T

g <- g + geom_signif(comparisons = compared_list, test = t.test, step_increase = 0.2, map_signif_level=T)


## 03 加上散点的信息

g <- g + geom_jitter(aes(fill=name),width =0.2,shape = 21,size=1)


## 04 去除网格线和背景，更改颜色

ggsci是ggplot的主题包，它提供一系列高质量的调色板，其灵感来自于科学期刊、数据可视化库、科幻电影和电视节目中使用的颜色。ggsci中的调色板可以作为ggplot2 scales使用。

#去除网格线和背景
g <- g+ theme_bw() + theme(panel.grid.major =element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(),axis.line = element_line(colour = "black"))
#更换颜色
library(ggsci)
g <- g + scale_fill_npg()


## 05 箱线图变带误差线、散点的柱形图

library(Rmisc)
input <- summarySE(res, measurevar="data", groupvars=c("name"))


data <- c(rnorm(99,10,3),rnorm(101,20,5))
name <- c(rep("control", 99),rep("treat",101))
res <- data.frame(data,name)
input <- summarySE(res, measurevar="data", groupvars=c("name"))
g <- ggplot(input, aes(name, data, fill=name)) +
geom_bar(position=position_dodge(), stat="identity") +
geom_errorbar(aes(ymin=data-se, ymax=data+se),
width=.3, # 设置误差线的宽度
position=position_dodge(.9)) +
theme_bw() +theme(panel.grid.major =element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(),axis.line = element_line(colour = "black"))


g <- g + geom_signif(comparisons = compared_list, test = t.test, step_increase = 0.2)  +
geom_jitter(data = res, aes(name,data,fill=name),width =0.2,shape = 21,size=1) +
geom_signif(data = res, aes(name,data),comparisons = compared_list, test = t.test, step_increase = 0.2)


g <- g +  scale_fill_aaas() +labs(subtitle="My final figure",x="Sample Name", y="Sample size")


05-19 8951

08-01 6451
04-03 1546
06-25 2万+
04-09 5万+
02-15 913