第四章 数据分布可视化

Author

221527110陈艺印

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 作图代码

library(e1071)     

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) # 添加注释文本

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

  • 图形:直方图展示 “eruptions” 数据分组频次,核密度曲线呈现分布形态,能快速把握数据集中趋势与离散程度 。偏度、峰度系数及均值线标注,帮助洞察数据偏离对称程度、陡峭程度和平均水平,深化对数据特征认知 。地毯图增加数据点分布细节,使数据整体感知更全面 。

  • 代码:熟悉ggplot语法,明确aes映射美学属性方式,以及各图层函数geom_histogram()、geom_density()等 的用法 。掌握对图形元素颜色、大小、线型等的设置,提升图形美观性与可读性 。学会结合统计函数“skewness、kurtosis、mean”与绘图代码,将统计分析融入图形展示 。

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=指标值) %>%  # 融合数据
  ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值并返回数据框

p1<-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) 原始数据的叠加直方图")

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_histogram(aes(x=eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制AQI的直方图(上图)
   geom_label(aes(x=20,y=0.1),label="AQI",color="red")+  # 添加标签
   geom_histogram(aes(x=waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制PM2.5的直方图(下图)
   geom_label(aes(x=60,y=-0.075),label="PM2.5",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(b) 原始数据的镜像直方图")

p2<-ggplot(df)+aes(x=x)+
   geom_histogram(aes(x=std.eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制AQI的直方图(上图)
   geom_label(aes(x=-0.5,y=0.5),label="AQI",color="red")+  # 添加标签
   geom_histogram(aes(x=std.waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制PM2.5的直方图(下图)
   geom_label(aes(x=-0.5,y=-0.5),label="PM2.5",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(b) 标准化的镜像直方图")


grid.arrange(p1,p2,ncol=2) 

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

  • 图形:对比原始与标准化数据的直方图,直观看到标准化改变数据分布形态与尺度,利于不同量级数据间比较 。叠加直方图展示不同指标分布及重叠情况;镜像直方图通过上下分布,清晰区分不同指标,避免视觉混淆 。

  • 代码:学会用gather融合数据、scale标准化数据,理解mutate在新增标准化变量中的作用 。掌握ggplot中aes映射美学属性,geom_histogram绘制直方图参数设置 ;熟悉图例位置、背景等细节调整,以及添加标题、标签方法,提升图表可读性 。通过grid.arrange实现多图并排展示,优化图表呈现布局 。

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="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) 原始数据的叠加直方图")

p2<-ggplot(df)+aes(x=标准化值,y=..density..,fill=指标)+
  geom_density(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)    

4.3 分面核密度图

ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
  geom_density(position="identity",color="gray60",alpha=0.5)+
  scale_fill_brewer(palette = "Set3")+
  facet_wrap(~指标,scale="free")+
  guides(fill="none")+
  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)
  )
  
p1<-ggplot(df)+aes(x=x)+
   geom_density(aes(x=eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制AQI的直方图(上图)
   geom_label(aes(x=20,y=0.1),label="AQI",color="red")+  # 添加标签
   geom_density(aes(x=waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制PM2.5的直方图(下图)
   geom_label(aes(x=60,y=-0.075),label="PM2.5",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(b) 原始数据的镜像直方图")

p2<-ggplot(df)+aes(x=x)+
   geom_density(aes(x=std.eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制AQI的直方图(上图)
   geom_label(aes(x=-0.5,y=0.5),label="AQI",color="red")+  # 添加标签
   geom_density(aes(x=std.waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制PM2.5的直方图(下图)
   geom_label(aes(x=-0.5,y=-0.5),label="PM2.5",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(b) 标准化的镜像直方图")


grid.arrange(p1,p2,ncol=2) 

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

  • 图形:通过密度曲线能直观看到 eruptions 和 waiting 等变量的数据分布形态,像原始数据与标准化数据的对比,可清晰察觉数据标准化前后分布特征的变化,如标准化后数据集中在均值附近。叠加直方图可对比不同类别数据分布重叠情况;镜像直方图能展示不同变量在正负方向的分布差异,便于发现变量间关系与特征 。

  • 代码:数据融合(gather 函数)与标准化(scale 函数)操作是关键步骤,为后续绘图准备合适格式的数据,且 dplyr 系列函数(如 ddply )使数据处理更流畅。ggplot2 包绘图语法清晰,通过 aes 映射图形属性,不同几何对象(geom_density 等)组合实现多样图形绘制。同时,对图例(legend.position 等参数)、标题(ggtitle )等细节设置,能让图形更美观规范。

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 箱线图代码

mytheme<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
   axis.title=element_text(size=10),               # 设置坐标轴标签字体大小
   axis.text=element_text(size=9),                # 设置坐标轴刻度字体大小
   legend.text=element_text(size="8"))            # 设置图例字体大小

df<-faithful %>%
  gather(key=指标,value=指标值) %>% 
  mutate(指标=factor(指标, levels = c("eruptions", "waiting")))%>%
  ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值并返回数据框

palette<-brewer.pal(6, "Set2")[1:2]     # 采用调色板前两种颜色

p1<-ggplot(df,aes(x=指标,y=指标值,fill = 指标))+
  geom_boxplot(fill=palette)+      # 绘制箱线图并设置填充颜色
  stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
ggtitle("(a) 原始数据镜像核密度图")

p2<-ggplot(df,aes(x=指标,y=标准化值,fill = 指标))+
  geom_boxplot(fill=palette)+      # 绘制箱线图并设置填充颜色
  stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
ggtitle("(b) 标准化数据镜像核密度图")

gridExtra::grid.arrange(p1,p2,ncol=2)  

5.3 小提琴图代码

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

# 设置图形主题
mytheme<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
   axis.title=element_text(size=10),               # 设置坐标轴标签字体大小
   axis.text=element_text(size=9),                # 设置坐标轴刻度字体大小
   legend.text=element_text(size="8"))            # 设置图例字体大小

fill_colors <- brewer.pal(6, "Set2")[1:2]

# 图(a)原始数据小提琴图
p1<-ggplot(df,aes(x=指标,y=指标值,fill=指标))+
     geom_violin(scale="width",trim=FALSE)+
     geom_point(color="black",size=1.5,alpha=0.4)+  # 添加点
     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")+
     stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
     geom_dotplot(aes(x=as.numeric(指标)-0.08,group=指标),
               width=0.5,binaxis="y",binwidth=2.5,stackdir="down")+
     ggtitle("(b) 标准化小提琴图")

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

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

  • 图形:镜像核密度图直观展现了数据在标准化前后的离散程度和集中趋势变化,标准化后数据分布更具可比性。小提琴图结合了箱线图与核密度图的优势,不仅呈现了数据的分布范围、四分位数等信息,还展示了数据的分布形状,能从多个角度洞察数据特征。

  • 代码:在代码编写过程中,熟练掌握ggplot2绘图语法是关键,其丰富的图层函数可灵活组合出各类复杂图形。数据预处理环节,如使用gather融合变量、mutate转换因子水平以及ddply计算标准化值等操作,为后续绘图奠定基础。

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

p1 <- ggplot(df, aes(x = 指标, y = 标准化值, fill = 指标)) +
  geom_dotplot(binaxis = "y", bins = 30, dotsize = 0.3, stackdir = "center") +
  mytheme +
  ggtitle("(a) 居中堆叠(标准化数据)")

p2 <- ggplot(df, aes(x = 指标, y = 标准化值, fill = 指标)) +
  geom_dotplot(binaxis = "y", bins = 30, dotsize = 0.3) +
  mytheme +
  ggtitle("(b) 向上堆叠(标准化数据)")

gridExtra::grid.arrange(p1,p2,ncol=2)

6.3 蜂群图代码

mytheme<-theme_bw()+theme(legend.position="none")
# 处理数据
df<-data |> 
  gather(eruptions,waiting,key=指标,value=指标值) |> 
  ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值并返回数据框

# 图(a)5项指标的蜂群图
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)

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) 水平排列")

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

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

  • 图形:蜂群图能直观展现数据点分布,带箱线图的蜂群图更可兼顾数据整体分布与离散特征;云雨图融合了小提琴图和点图优势,垂直与水平排列能从不同视角呈现数据分布形态;点图的不同堆叠方式,让数据分布的疏密情况一目了然。这些图形从多种角度揭示了eruptionswaiting变量标准化后的数据特征,有助于全面理解数据内在规律。

  • 代码:数据处理上,gather函数或pivot_longer(更推荐)可方便实现数据长格式转换,scale函数用于标准化数据。可视化时,不同绘图函数(如geom_beeswarmgeom_violindotgeom_dotplot )参数设置十分关键,像点的大小、形状、填充颜色,箱宽、堆叠方向等,细微调整就能显著影响图形呈现效果。同时,自定义主题能统一风格、提升美观度,多图组合函数可高效布局展示,这些都提升了绘图的规范性与专业性。