统计学-基于R (第四版) 贾俊平编著 第二章: 数据可视化 2.1, 2.2 习题答案 【自用】

本文介绍了使用R语言进行数据可视化的案例,包括基于Titanic数据集的条形图、帕累托图、脊形图、马赛克图以及饼图等,展示了不同类型的图表制作技巧。同时,通过faithful数据集,探讨了直方图、核密度曲线、箱线图和茎叶图的绘制,帮助理解数据分布特征。
摘要由CSDN通过智能技术生成

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).

  • 12
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值