其他
R可视化——基于ggplot2绘制柱状图并根据分组添加不同背景色!
点击上方
“科研后花园”
关注我们
绘图代码如下:
1、设置工作环境
rm(list=ls())
setwd("D:\\柱状图")
2、加载包
library(ggplot2) # Create Elegant Data Visualisations Using the Grammar of Graphics
library(reshape2) # Flexibly Reshape Data: A Reboot of the Reshape Package
3、构造数据
df <- read.table("data2.txt",header = T, check.names = F)
data=melt(df)
#误差棒这里我们随机编写,无实际意义
data$er=data$value/10
4、绘图
ggplot(data,aes(variable,value,fill=group))+
geom_bar(size = 1.5,position="dodge", stat="identity",width = 0.8)+#绘制柱状图
geom_errorbar(aes(ymin = value-er, ymax = value+er,color=group),
width = 0.2,position = position_dodge(width = 0.8),cex=1.2)+ #添加误差棒
labs(x="",y=NULL)+#去除轴标题
theme_bw()+#主题
theme(panel.grid=element_blank(),
axis.text=element_text(color='#333c41',size=12),
legend.text = element_text(color='#333c41',size=12),
legend.title = element_text(color='red',size=13))+
scale_y_continuous(expand = c(0, 0), limit = c(0, 23))+#去除网格线
#为更直观展示分组,添加方块
annotate("rect", xmin = 0.5, xmax = 1.5, ymin = 0, ymax = 23, alpha = 0.4,fill="#dde2e0") +
annotate("rect", xmin = 1.5, xmax = 2.5, ymin = 0, ymax = 23, alpha = 0.4,fill="#0081b4") +
annotate("rect", xmin = 2.5, xmax = 3.5, ymin = 0, ymax = 23, alpha = 0.4,fill="#96cbb3") +
annotate("rect", xmin = 3.5, xmax = 4.5, ymin = 0, ymax = 23, alpha = 0.4,fill="#91be3e") +
scale_fill_manual(values=c("#004a77","#00adee","#ff8100"))+#自定义柱状图颜色
scale_color_manual(values=c("#004a77","#00adee","#ff8100"))+#自定义误差棒颜色
#手动添加显著性标记,图中列出部分,具体根据个人数据进行调整
annotate('text', label = '**', x =0.65, y =21, angle=-90, size =5,color="#004a77")+
annotate('text', label = '***', x =2.9, y =21, angle=-90, size =5,color="#00adee")
温馨提示
如果你喜欢本文,请分享到朋友圈,想要获得更多信息,请关注我。