R 语言柱状图示例笔记
阅读原文时间:2023年08月11日阅读:3

由于微信不允许外部链接,你需要点击文章尾部左下角的 "阅读原文",才能访问文章中链接。

1. barplot 命令

基于barplot基础柱状图颜色、方向及分组的绘图示例。

par(mfrow=c(2,2))counts&nbsp;<-&nbsp;table(mtcars$gear)barplot(counts,&nbsp;main="Car&nbsp;Distribution",&nbsp;xlab="Number&nbsp;of&nbsp;Gears")barplot(counts,&nbsp;main="Car&nbsp;Distribution",&nbsp;horiz=TRUE,names.arg=c("3&nbsp;Gears",&nbsp;"4&nbsp;Gears",&nbsp;"5&nbsp;Gears"),col="blue")counts2&nbsp;<-&nbsp;table(mtcars$vs,&nbsp;mtcars$gear)barplot(counts2,&nbsp;main="Car&nbsp;Distribution&nbsp;by&nbsp;Gears&nbsp;and&nbsp;VS",xlab="Number&nbsp;of&nbsp;Gears",&nbsp;col=c("darkblue","red"),legend&nbsp;=&nbsp;rownames(counts2))barplot(counts2,&nbsp;main="Car&nbsp;Distribution&nbsp;by&nbsp;Gears&nbsp;and&nbsp;VS",xlab="Number&nbsp;of&nbsp;Gears",&nbsp;col=c("darkblue","red"),legend&nbsp;=&nbsp;rownames(counts2),beside=TRUE)

2. ggplot2 包绘制柱状图

使用ggplot2包的柱状图颜色、方向及分组的绘图示例。

library('ggplot2')p1<-ggplot(data=mtcars,aes(x=cyl,col=cyl))&nbsp;+&nbsp;geom_bar(stat="count",fill="white")&nbsp;+&nbsp;theme_bw()p2<-ggplot(data=mtcars,aes(x=cyl))&nbsp;+&nbsp;geom_bar(stat="count",fill="steelblue")&nbsp;+&nbsp;theme_bw()&nbsp;&nbsp;+&nbsp;coord_flip()p3<-ggplot(data=mtcars,aes(x=cyl,fill=cyl))&nbsp;+&nbsp;geom_bar(stat="count")&nbsp;+&nbsp;theme_bw()&nbsp;+scale_fill_manual(values=c("#999999",&nbsp;"#E69F00",&nbsp;"#56B4E9"))p4<-ggplot(data=mtcars,aes(x=cyl,fill=cyl))&nbsp;+&nbsp;geom_bar(stat="count")&nbsp;+&nbsp;theme_bw()&nbsp;+scale_fill_grey()&nbsp;+&nbsp;coord_flip()gridExtra::grid.arrange(p1,&nbsp;p2,p3,p4,nrow=2)

2.1 柱状图添加标签

data&nbsp;<-&nbsp;data.frame(table(mtcars$cyl))p1&nbsp;<-&nbsp;ggplot(data=newmatrix,aes(x=Var1,y=Freq,col=Var1))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity",fill="white")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_text(aes(label=Freq),&nbsp;vjust=1.6,&nbsp;color="black",&nbsp;size=5)p2&nbsp;<-&nbsp;ggplot(data=newmatrix,aes(x=Var1,y=Freq,fill=Var1))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()+&nbsp;geom_text(aes(label=Freq),vjust=-0.3,&nbsp;color="black",&nbsp;size=5)gridExtra::grid.arrange(p1,p2,nrow=1)

2.2 按组绘制柱状图

mtcars$am&nbsp;<-&nbsp;as.factor(mtcars$am)p1&nbsp;<-&nbsp;ggplot(data=mtcars,aes(x=cyl,y=mpg,fill=am))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()p2&nbsp;<-&nbsp;ggplot(data=mtcars,aes(x=cyl,y=mpg,fill=am))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity",position=position_dodge())&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;scale_fill_manual(values=c('#999999','#E69F00'))gridExtra::grid.arrange(p1,p2,nrow=1)

2.3 柱状图添加标签

counts2&nbsp;<-&nbsp;data.frame(table(mtcars$cyl,mtcars$am))p1&nbsp;<-&nbsp;ggplot(data=counts2,aes(x=Var1,y=Freq,fill=Var2))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_text(aes(label=Freq),&nbsp;vjust=5,position='stack',&nbsp;color="black",size=3.5)p2&nbsp;<-&nbsp;ggplot(data=counts2,aes(x=Var1,y=Freq,fill=Var2))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity",position=position_dodge())&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_bw()&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;scale_fill_brewer(palette="Paired")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;geom_text(aes(label=Freq),vjust=-0.3,&nbsp;color="darkblue",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;position=position_dodge(0.9),&nbsp;size=3.5)gridExtra::grid.arrange(p1,p2,nrow=1)

3. ggpubr 包绘制柱状图

library(ggpubr)dfm&nbsp;<-&nbsp;mtcarsdfm$cyl&nbsp;<-&nbsp;as.factor(dfm$cyl)dfm$name&nbsp;<-&nbsp;rownames(dfm)ggbarplot(dfm,&nbsp;x="name",&nbsp;y="mpg",fill="cyl",color="white",palette="jco",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sort.val="desc",sort.by.groups=FALSE,x.text.angle=90)

3.1 分组绘制柱状图

ggbarplot(dfm,&nbsp;x="name",&nbsp;y&nbsp;="mpg",&nbsp;fill="cyl",&nbsp;color="white",&nbsp;palette="jco",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sort.val="asc",&nbsp;sort.by.groups=TRUE,&nbsp;x.text.angle=90)

3.2 zsore 校正及分组

dfm$mpg_z&nbsp;<-&nbsp;(dfm$mpg&nbsp;-mean(dfm$mpg))/sd(dfm$mpg)dfm$mpg_grp&nbsp;<-&nbsp;factor(ifelse(dfm$mpg_z&nbsp;<&nbsp;0,&nbsp;"low",&nbsp;"high"),levels&nbsp;=&nbsp;c("low",&nbsp;"high"))ggbarplot(dfm,&nbsp;x&nbsp;=&nbsp;"name",&nbsp;y&nbsp;=&nbsp;"mpg_z",fill&nbsp;=&nbsp;"mpg_grp",&nbsp;color&nbsp;=&nbsp;"white",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;palette&nbsp;=&nbsp;"jco",&nbsp;sort.val&nbsp;=&nbsp;"asc",sort.by.groups&nbsp;=&nbsp;FALSE,x.text.angle&nbsp;=&nbsp;90,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ylab&nbsp;=&nbsp;"MPG&nbsp;z-score",xlab&nbsp;=&nbsp;FALSE,legend.title&nbsp;=&nbsp;"MPG&nbsp;Group")

3.3 图像旋转

ggbarplot(dfm,&nbsp;x&nbsp;=&nbsp;"name",&nbsp;y&nbsp;=&nbsp;"mpg_z",fill&nbsp;=&nbsp;"mpg_grp",color&nbsp;=&nbsp;"white",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;palette&nbsp;=&nbsp;"jco",sort.val&nbsp;=&nbsp;"desc",sort.by.groups&nbsp;=&nbsp;FALSE,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;x.text.angle&nbsp;=&nbsp;90,ylab&nbsp;=&nbsp;"MPG&nbsp;z-score",legend.title&nbsp;=&nbsp;"MPG&nbsp;Group",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;rotate&nbsp;=&nbsp;TRUE,ggtheme&nbsp;=&nbsp;theme_minimal())

1. barplot+segments+arrows 绘制误差线

1.1 绘制普通柱状图

  • 构建数据集

    myData <- aggregate(mtcars$mpg,by = list(cyl = mtcars$cyl, gears = mtcars$gear), FUN = function(x) c(mean = mean(x), sd = sd(x),n = length(x)))myData <- do.call(data.frame, myData)myData  cyl gears x.mean      x.sd x.n1   4     3 21.500        NA   12   6     3 19.750 2.3334524   23   8     3 15.050 2.7743959  124   4     4 26.925 4.8073604   85   6     4 19.750 1.5524175   46   4     5 28.200 3.1112698   27   6     5 19.700        NA   18   8     5 15.400 0.5656854   2

  • 计算标准差

    myData$se <- myData$x.sd / sqrt(myData$x.n)colnames(myData) <- c("cyl", "gears", "mean", "sd", "n", "se")myData$names <- c(paste(myData$cyl, "cyl /", myData$gears, " gear"))

  • 定义作图范围

    par(mar = c(5, 6, 4, 5) + 0.1)plotTop <- max(myData$mean) +myData[myData$mean == max(myData$mean), 6] * 3barCenters <- barplot(height = myData$mean, names.arg = myData$names,                        beside = true, las = 2, ylim = c(0, plotTop),                       cex.names = 0.75, xaxt = "n",                       main = "Mileage by No. Cylinders and No. Gears",                       ylab = "Miles per Gallon",  border = "black", axes = TRUE)

  • 横坐标

    text(x = barCenters, y = par("usr")[3] - 1, srt = 45,     adj = 1, labels = myData$names, xpd = TRUE)

  • Error bar

    segments(barCenters, myData$mean - myData$se  2, barCenters,         myData$mean + myData$se  2, lwd = 1.5)arrows(barCenters, myData$mean - myData$se  2, barCenters,       myData$mean + myData$se  2, lwd = 1.5, angle = 90,code = 3, length = 0.05)

1.2 按照分组绘制柱状图

tabbedMeans&nbsp;<-&nbsp;tapply(myData$mean,list(myData$cyl,myData$gears),function(x)&nbsp;c(x&nbsp;=&nbsp;x))tabbedSE&nbsp;<-&nbsp;tapply(myData$se,&nbsp;list(myData$cyl,&nbsp;myData$gears),function(x)&nbsp;c(x&nbsp;=&nbsp;x))barCenters&nbsp;<-&nbsp;barplot(height&nbsp;=&nbsp;tabbedMeans,beside&nbsp;=&nbsp;TRUE,&nbsp;las&nbsp;=&nbsp;1,ylim&nbsp;=&nbsp;c(0,&nbsp;plotTop),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cex.names&nbsp;=&nbsp;0.75,main&nbsp;=&nbsp;"Mileage&nbsp;by&nbsp;No.&nbsp;Cylinders&nbsp;and&nbsp;No.&nbsp;Gears",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ylab&nbsp;=&nbsp;"Miles&nbsp;per&nbsp;Gallon",xlab&nbsp;=&nbsp;"No.&nbsp;Gears",border&nbsp;=&nbsp;"black",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;axes&nbsp;=&nbsp;TRUE,legend.text&nbsp;=&nbsp;TRUE,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;args.legend&nbsp;=&nbsp;list(title&nbsp;=&nbsp;"No.Cylinders",x&nbsp;=&nbsp;"topright",cex&nbsp;=&nbsp;.7))segments(barCenters,&nbsp;tabbedMeans-tabbedSE*2,&nbsp;barCenters,tabbedMeans+tabbedSE*2,&nbsp;lwd&nbsp;=&nbsp;1.5)arrows(barCenters,&nbsp;tabbedMeans-tabbedSE&nbsp;*&nbsp;2,&nbsp;barCenters,tabbedMeans+tabbedSE*2,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;lwd&nbsp;=&nbsp;1.5,&nbsp;angle&nbsp;=&nbsp;90,code&nbsp;=&nbsp;3,&nbsp;length&nbsp;=&nbsp;0.05)

2. ggplot2 包绘带误差线的制柱状图

myData$gears&nbsp;<-&nbsp;as.factor(myData$gears)ggplot(myData,aes(x=cyl,y=mean,fill=gears))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_bar(stat="identity",position=position_dodge())&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;geom_errorbar(aes(ymin=mean-sd,ymax=mean+sd),width=.2,position=position_dodge(.9))&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;scale_fill_brewer(palette="Paired")&nbsp;+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;theme_minimal()

3. ggbarplot 绘制绘带误差线的制柱状图

ggbarplot(mtcars,x="cyl",y="mpg",color="am",add="mean_se",&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;palette=c("#00AFBB","#E7B800"),&nbsp;position=position_dodge())

柱状图的介绍就先到这里,其他可替代柱状图的图形包含棒棒糖图(Lollipop)、环形柱状图等未在本文中展开介绍,有兴趣的小伙伴可参考文章最后的参考资料。

  • Alboukadel Kassambara,《Bar Plots -R base Graphs》,STHDA

  • Selva Prabhakaran,《Top 50 ggplot2 Visualizations》,r-statistics.co

  • Alboukadel Kassambara,《ggpubr: Publication Ready Plots》,STHDA

  • Alboukadel Kassambara,《Plot Means/Medians and Error Bars》,STHDA

  • Alboukadel Kassambara,《ggplot2- barplot1》》,STHDA

  • Winston Chang,《ggplot2- barplot2》,Cookbook for R

  • Chris Wetherill,《Building Barplots with errorbars》,datascience+

  • SWD team,《bring on the bar charts — storytelling with data》,storytellingwithdata.com

本文分享自微信公众号 - 生信科技爱好者(bioitee)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器