第四章 数据分布可视化

Author

221527115杨诗婷

1 解释原始数据

  • faithful是R语言中自带的一个经典数据集,它记录了美国黄石国家公园老忠实间歇泉(Old Faithful geyser)的喷发数据。这个数据集经常被用于统计教学和数据分析示例。

  • faithful数据集包含两个变量,共有272个观测值。

    data = faithful
    datatable(data,rownames = FALSE)
  • eruptions: 喷发持续时间,连续数值变量,以分钟为单位,范围:1.6分钟到5.1分钟。

  • waiting: 两次喷发之间的等待时间,连续数值变量,以分钟为单位,范围:43分钟到96分钟。

2 单变量直方图

2.1 绘图要求

  • 利用geom_histogram(aes(y=..density..))绘制eruptions的直方图,使用预设主题:mytheme;

  • 利用geom_rug()为直方图添加地毯图;

  • 利用geom_density()为直方图添加核密度曲线;

  • 利用annotate()在直方图标注峰度和偏度信息;

  • 利用geom_vline() 为直方图添加一条垂直的均值参考线;

  • 利用geom_point()在横轴上添加一个中位数参考点,并在点上方添加文字注释

2.2 作图代码

df<-data
ggplot(data=df,aes(x=eruptions))+mytheme+
  geom_histogram(aes(y=..density..),fill="lightgreen",color="gray50")+
  geom_rug(size=0.2,color="blue3")+
  geom_density(color="blue2",size=0.7)+
  annotate("text",x=2.5,y=0.7,label=paste0("偏度系数 =",round(skewness(df$eruptions),4)),size=3)+  # 添加注释文本
  annotate("text",x=2.5,y=0.65,label=paste0("峰度系数 =",round(kurtosis(df$eruptions),4)),size=3)+  # 添加注释文本
  geom_vline(xintercept=mean(df$eruptions),linetype="twodash",size=0.6,color="red")+          # 添加均值垂线,并设置线形、线宽和颜色
  annotate("text",x=mean(df$eruptions),y=0.7,label=paste0("均值线=",round(mean(df$eruptions),2)),size=3)+
  geom_point(x=median(df$eruptions),y=0,shape=21,size=4,fill="yellow")+# 添加中位数点
  annotate("text",x=median(df$eruptions),y=0.05,label="中位数",size=3,color="red3") # 添加注释文本

2.3 图形观察和代码编写的心得体会

  • 直方图打底,一眼就能看出数据集中在哪;加上密度曲线后,整体走势更平滑清晰。地毯图虽然简单,但能清楚看到每个数据点的位置,比光看柱状图更细致。

    代码写起来挺顺手的,就像搭积木一样一层层往上加:

    1. 先用直方图框出大体分布

    2. 叠上密度曲线让走势更明显

    3. 加地毯图标出每个数据点

    4. 最后用文字标注关键数据特征

    几个实用小技巧:

    • 用paste0动态生成标注文字,改数据时不用手动调整

    • 颜色搭配要讲究:直方图用浅色打底,重点线用红色突出

    • 均值线用特殊线型,一眼就能找到

3 叠加直方图和镜像直方图

3.1 绘图要求

  • 绘制eruptionswaiting两个变量的叠加直方图和镜像直方图,使用预设主题:mytheme。

  • 将数据转化为长型数据再作叠加直方图,利用scale_fill_brewer()将叠加直方图配色方案改为set3

  • 镜像直方图中eruptions在正方向,waiting在负方向,直方数bins=30,并添加文字标签作标签。

  • 两种图都需要针对原始数据作图和标准标准化数据作图,可以使用scale()函数对变量标准化,分类标准化可以使用plyr::ddply()函数。

3.2 叠加直方图代码

df <- data |> 
  gather(eruptions,waiting,key=指标,value=指标值)   # 融合数据

 p1<-ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
  geom_histogram(position="identity",color="gray60",alpha=0.5)+
  theme(legend.position=c(0.8,0.8),# 设置图例位置
       legend.background=element_rect(fill="grey90",color="grey"))+
                                                # 设置图例背景色和边框颜色
  ggtitle("(a) 原始数据的叠加直方图")

p2<-ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
  geom_histogram(position="identity",color="gray60",alpha=0.5)+
  scale_fill_brewer(palette="Set3")+  
  theme(legend.position=c(0.8,0.8),# 设置图例位置
       legend.background=element_rect(fill="grey90",color="grey"))+
                                                # 设置图例背景色和边框颜色
  ggtitle("(a) 标准化数据的叠加直方图")
grid.arrange(p1,p2,ncol=2) 

3.3 镜像直方图代码

df<-data |> 
  mutate(
    std.eruptions=scale(eruptions) ,
    std.waiting=scale(waiting)
    )
p1<-ggplot(df,aes(x=x))+
   geom_density(aes(x=eruptions,y=..density..),fill="red",alpha=0.3,bin=30)+ # 绘制AQI的核密度图(上图)
   geom_label(aes(x=20,y=0.1),label="eruptions",color="red")+  # 添加标签
   geom_density(aes(x=waiting,y=-..density..),fill="blue",alpha=0.3,bin=30)+ # 绘制PM2.5的核密度图(下图)
   geom_label(aes(x=60,y=-0.075),label="waiting",color="blue")+
   xlab("指标值")+ggtitle("原始数据的镜像核密度图")

p2<-ggplot(df,aes(x=x))+
   geom_density(aes(x=std.eruptions,y=..density..),fill="red",alpha=0.3,bin=30)+ # 绘制AQI的核密度图(上图)
   geom_label(aes(x=0.5,y=0.5),label="eruptions",color="red")+  # 添加标签
   geom_density(aes(x=std.waiting,y=-..density..),fill="blue",alpha=0.3,bin=30)+ # 绘制PM2.5的核密度图(下图)
   geom_label(aes(x=-0.5,y=-0.5),label="waiting",color="blue")+
   xlab("指标值")+ggtitle("标准化数据镜像核密度图")
grid.arrange(p1,p2,ncol=2) 

3.4 图形观察和代码编写的心得体会

  • 画叠加直方图时,用melt()把eruptions和waiting两个变量堆成一列,再加上标识列,ggplot画起来就顺手多了镜像直方图的实现比想象中简单。把waiting的数据取反,再用coord_flip()翻转坐标轴,立马就呈现出完美的镜像效果。设置bins=30让分布曲线既不会太粗糙,也不会过度拟合。加上文字标注后,关键数据点变得特别醒目。

    用alpha参数调整透明度,能让重叠部分看得更清楚。这些经验以后画类似图表都能用上,特别是需要对比多个变量分布的时候。

4 核密度图

4.1 绘图要求

  • 绘制eruptions和 waiting两个变量的分组核密度图、分面核密度图和镜像核密度图。

  • 分组核密度图,采用geom_density(position="identity")

  • 分面核密度图,采用geom_density()+facet_wrap(~xx,scale="free")

  • 镜像核密度图中eruptions在正方向,waiting在负方向,直方数bins=30,并添加文字标签作标签。

  • 分组核密度图和镜像核密度图需要针对原始数据作图和标准标准化数据作图。

4.2 分组核密度图

df<-data |> 
  gather(eruptions,waiting,key=指标,value=指标值) %>%  # 融合为长格式
  ddply("指标",transform,标准化值=scale(指标值))

p1<-ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
   geom_density(position="identity",color="gray50",alpha=0.5)+
   scale_fill_brewer(palette="Set3")+           # 设置调色板
   theme(legend.position=c(0.8,0.8),
         legend.background = element_rect(fill="grey90",color="grey"))+

   ggtitle("原始数据的叠加直方图")

p2<-ggplot(df)+aes(x=标准化值,y=..density..,fill=指标)+
   geom_density(position="identity",color="gray50",alpha=0.5)+
   scale_fill_brewer(palette="Set3")+           # 设置调色板
   theme(legend.position=c(0.8,0.8),
         legend.background = element_rect(fill="grey90",color="grey"))+

   ggtitle("标准化数据的叠加直方图")
grid.arrange(p1,p2,ncol=2) 

4.3 分面核密度图

# 绘制按质量等级分组、按指标分面的核密度图
ggplot(df)+aes(x=标准化值,y=..density..,fill=指标)+
  geom_density(position="identity",color="gray50",alpha=0.5)+
  scale_fill_brewer(palette="Set3")+                    # 设置调色板
  theme(legend.position=c(0.8,0.8),
         legend.background = element_rect(fill="grey90",color="grey"))                     # 设置图例位置

4.4 镜像核密度图

df <- data |> 
mutate(
  std.eruptions=scale(eruptions),
  std.waiting=scale(waiting),
  )   # 融合数据

# 图(a)AQI和PM2.5的镜像核密度图
p1<-ggplot(df,aes(x=x))+
   geom_density(aes(x=eruptions,y=..density..),fill="red",alpha=0.3,bin=30)+ # 绘制AQI的核密度图(上图)
   geom_label(aes(x=20,y=0.1),label="eruptions",color="red")+  # 添加标签
   geom_density(aes(x=waiting,y=-..density..),fill="blue",alpha=0.3,bin=30)+ # 绘制PM2.5的核密度图(下图)
   geom_label(aes(x=60,y=-0.075),label="waiting",color="blue")+
   xlab("指标值")+ggtitle("(a) 原始数据的镜像核密度图")

# 图(b)二氧化氮和臭氧浓度的镜像核密度图(theme_classic())
p2<-ggplot(df)+aes(x=x)+
   geom_density(aes(x=std.eruptions,y=..density..),color="grey50",fill="red",alpha=0.3)+ # 绘制PM10的直方图(上图)
   geom_label(aes(x=0.5,y=0.5),label="eruptions",color="red")+  # 添加标签
geom_density(aes(x=std.waiting,y=-..density..),color="grey50",fill="blue",alpha=0.3)+ # 绘制臭氧浓度的直方图(下图)
   geom_label(aes(x=-0.5,y=-0.5),label="waiting",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(b) 标准化数据的镜像核密度图")

gridExtra::grid.arrange(p1,p2,ncol=2)        # 组合图形

4.5 图形观察和代码编写的心得体会

  • 分组核密度图:两变量曲线叠一起时,设透明色(alpha=0.5)才能看清重叠区。标准化后比较更准,不然量纲大的会把小的压成直线。

  • 分面图:用facet_wrap分开展示更清爽,但记得加scale=“free”,不然y轴刻度会打架。分面标签用strip.text调样式更美观。

  • 镜像图:waiting的密度值取反就能镜像,配合coord_flip()能横着看。标准化后的镜像对比效果最明显,一眼就能看出eruptions更尖、waiting更平。

  • 必用scale()先标准化,但别动原数据,新建列存标准化值,镜像图y轴标签会显示负值,用scale_y_continuous(labels=abs)转成正数,核密度带宽用adjust调,0.5~1.5之间试几次,找到最佳平滑度

5 箱线图和小提琴图

5.1 绘图要求

  • 根据实际数据和标准化后的数据绘制eruptionswaiting两个变量的箱线图geom_boxplot和小提琴图geom_violin

  • 采用stat_summary(fun="mean",geom="point")在箱线图和均值图中要添加均值点。

  • 小提琴图中要加入点图和箱线图

  • 采用调色板前两种颜色,brewer.pal(6,"Set2")[1:2] ,作为箱体填充颜色。

"#66C2A5" "#FC8D62" "#8DA0CB" "#E78AC3" "#A6D854" "#FFD92F"

5.2 箱线图代码

df <- data |>  
  gather(eruptions,waiting,key=指标,value=指标值)%>% #融合数据
  ddply("指标",transform,标准化值=scale(指标值))#计算标准化并返回数据框

palette<-RColorBrewer::brewer.pal(6,"Set2")[1:2]          # 设置离散型调色板
p1<-ggplot(df,aes(x=指标,y=指标值))+
  geom_boxplot(fill=palette)+      # 绘制箱线图并设置填充颜色
  stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
  xlab("指标值")+ggtitle("(a) 实际数据的箱线图")
                                                    # 添加均值点
p2<-ggplot(df,aes(x=指标,y=标准化值))+
  geom_boxplot(fill=palette)+      # 绘制箱线图并设置填充颜色
  stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
  xlab("指标值")+ggtitle("(b) 标准化数据的箱线图")
                                                   # 添加均值点
grid.arrange(p1,p2,ncol=2)

5.3 小提琴图代码

  • 通过d3r::d3_nest将数据框转化为层次数据“d3.js”作为绘图输入
df <- data |>  
  gather(eruptions,waiting,key=指标,value=指标值)%>% #融合数据
  ddply("指标",transform,标准化值=scale(指标值))#计算标准化并返回数据框

# 图(a)原始数据小提琴图
p1<-ggplot(df,aes(x=指标,y=指标值,fill=指标))+
     geom_violin(scale="width",trim=FALSE)+
     geom_point(color="black",size=0.8)+  # 添加点
     geom_boxplot(outlier.size=0.7,outlier.color="white",size=0.3,
               width=0.2,fill="white")+  # 添加并设置箱线图和离群点参数
     scale_fill_brewer(palette="Set2")+
     stat_summary(fun=mean,geom="point",shape=21,size=2)+# 添加均值点
     guides(fill="none")+
     ggtitle("(a) 原始数据小提琴图")

# 图(b)数据标准化后的小提琴图
p2<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
     geom_violin(scale="width")+
     #geom_point(color="black",size=1)+
     geom_boxplot(,outlier.size=0.7,outlier.color="black",size=0.3,
          width=0.2,fill="white")+
     scale_fill_brewer(palette="Set2")+
     guides(fill="none")+
     ggtitle("(b) 标准化小提琴图")

gridExtra::grid.arrange(p1,p2,ncol=2)        # 组合图形p1和p2

5.4 图形观察和代码编写的心得体会

6 威尔金森点图、蜂群图和云雨图

6.1 绘图要求

  • 绘制eruptionswaiting 两个变量的威尔金森点图、蜂群图和云雨图。

  • 三种图形均采用标准化数据作图

  • 威尔金森点图采用geom_dotplot(binaxis="y",bins=30,dotsize = 0.3) ,要求作出居中堆叠和向上堆叠两种情况的图。

  • 蜂群图采用geom_beeswarm(cex=0.8,shape=21,size=0.8),要求作出不带箱线图和带有箱线图两种情况的图。

  • 云雨图采用geom_violindot(dots_size=0.7,binwidth=0.07) ,要求作出横向和纵向图两种情况的图。

6.2 威尔金森点图代码

分别作矩形热图和极坐标热图

mytheme<-theme_bw()+theme(legend.position="none")

df <- data |>  
  gather(eruptions,waiting,key=指标,value=指标值)%>% #融合数据
  ddply("指标",transform,标准化值=scale(指标值))#计算标准化并返回数据框

# 绘制图形
mytheme<-theme_bw()+theme(legend.position="none")
p<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))
p1<-p+geom_dotplot(binaxis="y",bins=30,dotsize = 0.3,stackdir="center")+ # 绘制点图
  mytheme+ggtitle("(a) 居中堆叠")

p2<-p+geom_dotplot(binaxis="y",bins=30,dotsize=0.3)+ # 绘制点图
  mytheme+ggtitle("(b) 向上堆叠")

gridExtra::grid.arrange(p1,p2,ncol=2)        # 组合图形p1和p2

6.3 蜂群图代码

mytheme<-theme_bw()+theme(legend.position="none")

df <- data |>  
  gather(eruptions,waiting,key=指标,value=指标值)%>% #融合数据
  ddply("指标",transform,标准化值=scale(指标值))#计算标准化并返回数据框

# 图(a)5项指标的蜂群图
mytheme<-theme_bw()+theme(legend.position="none")
p<-ggplot(df,aes(x=指标,y=标准化值))
p1<-p+geom_beeswarm(cex=0.8,shape=21,fill="black",size=0.8,aes(color=指标))+# 设置蜂群的宽度、点的形状、大小和填充颜色
mytheme+ggtitle("(a) 蜂群图")

# 图(b)箱线图+蜂群图
p2<-p+geom_boxplot(size=0.5,outlier.size=0.8,aes(color=指标))+
geom_beeswarm(shape=21,cex=0.8,size=0.8,aes(color=指标))+
mytheme+ggtitle("(b) 箱线图+蜂群图")

gridExtra::grid.arrange(p1,p2,ncol=2)        # 组合图形p1和p2

6.4 云雨图代码

library(see)  # 提供主题函数theme_modern
mytheme<-theme_modern()+
         theme(legend.position="none",
               plot.title=element_text(size=14,hjust=0.5))   # 调整标题位置

df <- data |>  
  gather(eruptions,waiting,key=指标,value=指标值)%>% #融合数据
  ddply("指标",transform,标准化值=scale(指标值))#计算标准化并返回数据框

p1<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
  geom_violindot(dots_size=0.7,binwidth=0.07)+ # 绘制云雨图并设置点的大小和箱宽
  mytheme+ggtitle("(a) 垂直排列(默认)")

p2<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
  geom_violindot(dots_size=0.7,binwidth=0.07)+
  coord_flip()+mytheme+ggtitle("(b) 水平排列")

gridExtra::grid.arrange(p1,p2,ncol=2)        # 按2列组合图形p1和p2

6.5 图形观察和代码编写的心得体会

  • 威尔金森点图

    • 观察:点堆叠后能直观看出数据分布密度,居中堆叠对称美观,向上堆叠更易比较两个变量。

    • 代码geom_dotplot(binaxis="y")控制堆叠方向,dotsize调整点大小避免重叠。标准化后两个变量能放同一坐标系比较。

    蜂群图

    • 观察:点自动避让排布,比散点图更清晰。加箱线图后能同时看到统计量(中位数、四分位数)。

    • 代码geom_beeswarm()画蜂群图,cex调点距;叠加geom_boxplot()增加统计信息。

    云雨图

    • 观察:小提琴图展示分布形状,内部点图显示具体数据。横向适合变量对比,纵向适合单变量深度分析。

    • 代码geom_violindot()一键组合云雨图,binwidth调点密度。转置坐标(coord_flip())变横向。

    心得

    1. 标准化数据是神器,不同量纲的变量也能同框对比。

    2. 点图类(威尔金森、蜂群)适合中小数据集,大数据会糊。

    3. 云雨图是”豪华版”箱线图,展示信息更丰富,但代码稍复杂。

    4. 多试参数(如dotsizecex),找到最佳视觉效果。