library(gridExtra)
library(e1071) # 用于计算偏度系数和峰度系数
library(ggplot2)
df <- penguins
mytheme<-theme(plot.title=element_text(size="12"), # 设置主标题字体大小
axis.title=element_text(size=10), # 设置坐标轴标签字体大小
axis.text=element_text(size=9), # 设置坐标轴刻度字体大小
legend.text=element_text(size="8")) # 设置图例字体大小
# 作初始直方图,纵轴默认为频数
h1<-ggplot(data=df,aes(x=`体重(g)`))+mytheme+ # 绘制直方图
geom_histogram(fill="lightgreen",color="gray50")
# 图(a) 添加地毯图、偏度系数和峰度系数
p1<-h1+geom_rug(size=0.2,color="blue3")+ # 添加地毯图,须线的宽度为0.2
annotate("text",x=210,y=37,label="偏度系数 =",size=2)+ # 添加注释文本
annotate("text",x=1000,y=37,label=round(skewness(df$`体重(g)`),4),size=2)+ # 添加偏度系数
annotate("text",x=210,y=33,label="峰度系数 =",size=2)+ # 添加注释文本
annotate("text",x=1000,y=33,label=round(kurtosis(df$`体重(g)`),4),size=2)+ # 添加峰度系数
ylab("count")+ggtitle("(a) 添加地毯图和偏度与峰度系数")
# 图(b)添加频数多边形中位数点
p2<-h1+geom_freqpoly(color="red3")+
geom_point(x=median(df$`体重(g)`),y=0,shape=21,size=4,fill="yellow")+# 添加中位数点
annotate("text",x=median(df$`体重(g)`),y=4.2,label="中位数",size=3,color="red3")+ # 添加注释文本
ggtitle("(b) 添加频数多边形和中位数点")
# 将直方图的纵轴转为密度
h2<-ggplot(data=df,aes(x=`体重(g)`))+mytheme+
geom_histogram(aes(y=..density..),fill="lightgreen",color="gray50")
# 图(c) 添加核密度曲线
p3<-h2+geom_density(color="blue2",size=0.7)+ # 添加核密度曲线
annotate("segment",x=2000,xend=2500,y=0.006,yend=0.001,color="blue",size=0.6,arrow=arrow(angle=15,length=unit(0.1,"inches")))+ # 添加带箭头的线
annotate("text",x=2000,y=0.0015,label="核密度曲线",size=2)+ # 添加注释文本
ggtitle("(c) 添加核密度曲线")
# 图(d) 添加理论正态曲线和均值线
p4<-h2+stat_function(fun=dnorm,args=list(mean=mean(df$`体重(g)`),sd=sd(df$`体重(g)`)),
linetype="twodash",color="red2",size=0.8)+ # 添加理论正态分布曲线
geom_vline(xintercept=mean(df$`体重(g)`),linetype="twodash",size=0.6,color="red")+ # 添加均值垂线,并设置线形、线宽和颜色
annotate("text",x=4500,y=0.01,label="均值线",size=3)+ # 添加注释文本
annotate("text",x=3000,y=0.0017,label="理论正态分布曲线",size=2)+ # 添加注释文本
ggtitle("(d) 添加理论正态曲线和均值线")
gridExtra::grid.arrange(p1,p2,p3,p4,ncol=2) # 按2列组合图形p1和p2