數據是自己隨便編的,需要準備一個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
由于數據是自己編的,畫出來的圖數據顯示的不是很好。