美文网首页
R 如何绘制箱线图

R 如何绘制箱线图

作者: 小qqq | 来源:发表于2022-06-26 18:21 被阅读0次

数据是自己随便编的,需要准备一个txt文件
BMI.txt


image.png

简单柱状图绘制

BMI=read.table("BMI.txt",header = T,row.names=1,sep="\t")
library(ggplot2)
BMI$name=rownames(BMI)

ggplot(BMI,aes(x=gender,y=height))+
  geom_boxplot()
#改变宽度

ggplot(BMI,aes(x=gender,y=height))+
  geom_boxplot(width=0.3)

p=ggplot(BMI,aes(x=gender,y=height))+
  geom_boxplot()
p
image.png

参数调整

#颠倒
p+coord_flip()
#添加均值
p+stat_summary(fun=mean,geom="point",shape=20,size=4,color="red")
#添加数据点,在中线上分布
p+geom_dotplot(binaxis = 'y',stackdir='center',dotsize = 1,binwidth = 0.5)

#添加数据点随机分布
p+geom_jitter(shape=16,position = position_jitter(0.2))

#设置边框的颜色
p<-ggplot(BMI,aes(x=gender,y=height,color=gender))+
  geom_boxplot()
p+scale_colour_brewer(palette = "Set1")
#手动设置颜色
p+scale_colour_manual(values = c("red","blue"))
#使用配色方案
p+scale_color_brewer(palette = "Dark2")
#使用灰色和经典主题
p+scale_colour_grey()+theme_classic()
#使用单一填充色
ggplot(BMI,aes(x=gender,y=height))+
  geom_boxplot(fill="grey",color="black")+
  theme_classic()
#根据分组设置填充色
p<-ggplot(BMI,aes(x=gender,y=height,fill=gender))+
  geom_boxplot()
p

如何美化

#美化
theme_bw()
scale_fill_manual(values = c("#DE6757","#5B9BD5"))
#去掉画布网格:
theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())
#坐标轴字号
theme(axis.title.x =element_text(size=14,face = "bold"), axis.title.y=element_text(size=14,face = "bold"),axis.text = element_text(size = 14,face = "bold"))
#横纵坐标轴标注:labs(x="Group", y="TL value")
#代码如下:
ggplot(data,aes(x=variable,y=value,fill=gender)) + 
geom_boxplot()+  geom_signif(comparisons = list(c("weight","BMI")),map_signif_level = TRUE,test = t.test,y_position = c(80,30),tip_length = c(0.05,0.4))+  theme_bw()+  
scale_fill_manual(values = c("#DE6757","#5B9BD5"))+ 
theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank())+  labs(x="Group", y="TL value")+ 
theme(axis.title.x =element_text(size=12,face = "bold"), axis.title.y=element_text(size=12,face = "bold"),axis.text = element_text(size = 12,face = "bold"))

如何画一张好看的箱线图:

BMI=read.table("BMI.txt",header = T,row.names=1,sep="\t")
library(ggplot2)
BMI$name=rownames(BMI)
BMI=BMI[,-6]
BMI
library(reshape2)
library(ggpubr)
library(ggsignif)
data=melt(BMI,id="gender")
p<-ggplot(data,aes(x=variable,y=value,fill=gender))+
  geom_boxplot()+
  geom_jitter(shape=16,position = position_jitter(0.2))+
  stat_boxplot(geom = "errorbar")+#添加误差线
  stat_compare_means(method = "t.test", label="p.signif")+
  theme_bw()+ #去掉灰色的背景
  theme(panel.grid=element_blank())+
  scale_fill_brewer(palette = "Dark2")
pdf("phe.pdf",width = 12,height = 8)
ggarrange(p, ncol = 2, nrow = 2)
dev.off()
image.png

由于数据是自己编的,画出来的图数据显示的不是很好。

相关文章

网友评论

      本文标题:R 如何绘制箱线图

      本文链接:https://www.haomeiwen.com/subject/axkovrtx.html