2.1 用R自带的Titanic绘制图形
数据和包准备
library(DescTools)
dataframeT = Untable(Titanic) #转为数据框形式
1. Sex 和 Survived 并列条形图 和 堆叠条形图,并添加频数标签
代码里没有调整 Male Femal 图例的大小,只做了 grey80 的框
par(mfrow=c(2,2),cex=1,mgp=c(2,1,0),cex.axis=0.8,cex.main=0.7,font.main=1) #页面布局
tb1 <- table(dataframeT$Sex,dataframeT$Survived) #生成频数表
b1 <- barplot(tb1,beside=TRUE,xlab="Survived",ylab = "人数",main="2.1.1 (a)垂直并列图",col=c("#66C2A5","#FC8D62"),legend=rownames(tb1),args.legend = list(box.col="grey80")) #垂直并列条形图
BarText(tb1,b=b1,beside=TRUE,cex=1,pos=c("mid")) #t加频数标签
b2 <- barplot(tb1,beside=TRUE,horiz=TRUE,xlab="人数",ylab = "Survived",main="2.1.1 (b)水平并列图",col=c("#66C2A5","#FC8D62"),legend=rownames(tb1),args.legend = list(box.col="grey80")) #水平并列条形图
BarText(tb1,b=b2,beside=TRUE,horiz = TRUE,cex=1,pos=c("mid"))
b3 <- barplot(tb1,xlab="Survived",ylab = "人数",main="2.1.1 (c)垂直堆叠图",col=c("#66C2A5","#FC8D62"),legend=rownames(tb1),args.legend = list(box.col="grey80")) #垂直堆叠条形图
BarText(tb1,b=b3,cex=1,pos=c("mid"))
b4 <- barplot(tb1,horiz=TRUE,xlab="人数",ylab = "Survived",main="2.1.1 (d)水平堆叠图",col=c("#66C2A5","#FC8D62"),legend=rownames(tb1),args.legend = list(box.col="grey80")) #水平堆叠条形图
BarText(tb1,b=b4,horiz=TRUE,cex=1,pos=c("mid"))
BarText() 的参数 pos 可以决定 bartext 所处的 位置。
> pos
one of “topout”, “topin”, “mid”, “bottomin”, “bottomout”, defining if the labels should be placed on top of the bars (inside or outside) or at the bottom of the bars (inside or outside).