基本簡介
分組柱狀圖,又叫聚合柱狀圖。當(dāng)需要在同一個(gè)軸上顯示各個(gè)分類下不同的分組時(shí),需要用到分組柱狀圖,是學(xué)術(shù)論文中常用的圖。每個(gè)分組中的柱子使用不同的顏色或者相同顏色不同透明的方式區(qū)別各個(gè)分類,各個(gè)分組之間需要保持間隔。
基本用法
利用ggplot2包進(jìn)行繪制,這里不贅述。
示例
##批量加載包
{library(ggplot2)
library(reshape2)
library(cowplot)
}
#清空
rm(list = ls())
##載入iris數(shù)據(jù)
data <- iris
###melt()函數(shù)重新融合數(shù)據(jù)
df <- melt(data, id="Species", variable.name="Attribute", value.name = "Size")
head(df)
##計(jì)算3種鳶尾花形態(tài)數(shù)據(jù)數(shù)據(jù)均值、標(biāo)準(zhǔn)差
mean <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=mean)
sd <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=sd)
###計(jì)算3種鳶尾花的個(gè)數(shù)
len <- aggregate(df$Size, by=list(df$Species, df$Attribute), FUN=length)
##合并均值和標(biāo)準(zhǔn)差為數(shù)據(jù)格式
df_res <- data.frame(mean, sd=sd$x, len=len$x)
##為合并好的數(shù)據(jù)命名列名
colnames(df_res) = c("Species", "Attribute", "Mean", "Sd", "Count")
##查看合并并命名后的數(shù)據(jù)
df_res
###計(jì)算3種鳶尾花的標(biāo)準(zhǔn)誤se=sd/sqrt(n)
df_res$Se <- df_res$Sd/sqrt(df_res$Count)
#######繪圖#########
##########用SE(標(biāo)準(zhǔn)誤差/標(biāo)準(zhǔn)誤)進(jìn)行作圖###########
a<-ggplot(df_res, aes(x=Attribute, y=Mean, fill=Species)) +
geom_bar(stat="identity", position=position_dodge(),
color="black", width=.8) +
geom_errorbar(aes(ymin=Mean-Se, ymax=Mean +Se),
position=position_dodge(.8), width=.2) +
theme_bw()+
scale_y_continuous(expand=c(0,0))+
coord_cartesian(ylim = c(0, 8))+
theme(axis.text.x = element_text(size = 14, color = "black"))+##設(shè)置x軸字體大小
theme(axis.text.y = element_text(size = 14, color = "black"))+##設(shè)置y軸字體大小
theme(title=element_text(size=13))+#設(shè)置標(biāo)題字體大小
theme_bw()
a
##########用SD(標(biāo)準(zhǔn)偏差/標(biāo)準(zhǔn)差)進(jìn)行作圖###########
b<-ggplot(df_res, aes(x=Attribute, y=Mean, fill=Species)) +
geom_bar(stat="identity", position=position_dodge(),
color="black", width=.8) +
geom_errorbar(aes(ymin=Mean-Sd, ymax=Mean +Sd),
position=position_dodge(.8), width=.2) +
theme_bw()+
scale_y_continuous(expand=c(0,0))+
coord_cartesian(ylim = c(0, 8))+
theme(axis.text.x = element_text(size = 14, color = "black"))+##設(shè)置x軸字體大小
theme(axis.text.y = element_text(size = 14, color = "black"))+##設(shè)置y軸字體大小
theme(title=element_text(size=13))+#設(shè)置標(biāo)題字體大小
theme_bw()
b
#######合并兩張圖#########
plot_grid(a, b, labels = LETTERS[1:2])
#######合并四張圖#########
plot_grid(a, b, a, b, labels = LETTERS[1:4])
#保存圖片
ggsave('Result.png')
參考文獻(xiàn)
[1] https://www.rdocumentation.org/packages/ggplot2/versions/3.3.5
[2] https://ggplot2-book.org/preface-to-the-second-edition.html