1、生成模拟数据
library(magrittr)
age1<-rnorm(100,60,10) %>% round
age2<-rnorm(100,70,15) %>% round
sex<-sample(c(1,2),100,replace=T)
weight<-sample(c(1,2,3),100,replace=T)
result<-rnorm(100,140,30)
group<-rep(c(1,2),50)
data<-cbind(age1,age2,sex,weight,result,group) %>% data.frame
data$sex<-factor(data$sex)
data$weight<-factor(data$weight)
data$id<-rownames(data)
2、绘制简单的箱线图
#简单的条形图
boxplot(result~sex,data=data)
#多个条件下的分组的条形图
boxplot(result~sex*weight,data=data)
#绘制分亚组的条形图
library(ggplot2)
ggplot(data, aes(x=weight, y=result, color=sex, fill=sex)) +
geom_boxplot(alpha = .5) + #半透明
theme_classic() #去除网格线
3、实现短表转化为长表
#长表和短表的互换(融合)
library(reshape2)
md<-melt(data,id=c("id","group"))[1:200,]
library(ggplot2)
str(md)
md$group<-factor(md$group)
md$value<-as.numeric(md$value)
ggplot(md, aes(x=variable, y=value, color=group, fill=group)) +
geom_boxplot(alpha = .5) + #半透明
theme_classic()
4、高级绘图
#高级绘图
#1、添加散点
ggplot(md, aes(x=variable,y=value,color=group,fill=group)) +
geom_boxplot(fill="white",alpha = 0.5) + #白色填充,设置为半透明
theme_classic()+
geom_point(shape = 21, size=.5, # 点的形状和大小
position = position_jitterdodge(), # 让点散开
alpha = .5)
#2、添加误差线:设置箱线图的大小和误差线的大小一致就能重合
ggplot(md, aes(x=variable,y=value,color=group,fill=group)) +
stat_boxplot(geom="errorbar",width=0.5,position = "dodge")+
geom_boxplot(alpha = 0.5,width=0.5,notch=T) + #白色填充,设置为半透明
theme_classic()+
geom_point(shape = 21, size=.5, # 点的形状和大小
position = position_jitterdodge(), # 让点散开
alpha = .5)
#3、组间比较,有统计学意义的添加标记
library(ggpubr)
ggplot(md, aes(x=variable,y=value,color=group,fill=group)) +
stat_boxplot(geom="errorbar",width=0.5,position = "dodge")+
geom_boxplot(alpha = 0.5,width=0.5,notch=T) + #白色填充,设置为半透明
theme_classic()+
geom_point(shape = 21, size=.5, # 点的形状和大小
position = position_jitterdodge(), # 让点散开
alpha = .5)+
ylim(0,120)+
stat_compare_means(aes(group = group),
label.y = c(120,120),
label = "p.signif",
method = "t.test")