第四章 数据分布可视化

Author

221527104+张浩宜

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)  # 用于计算偏度系数和峰度系数
library(ggplot2)

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") + 
  # 添加地毯图,须线的宽度为0.2
  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 图形观察和代码编写的心得体会

多维度展示:直方图+核密度曲线+地毯图能同时呈现数据分布、密度和具体数值位置

统计量可视化:均值线和统计量标注使图形分析更直观

2.4 参数协调:颜色(lightgreen/blue3/red)、线型(twodash)、大小(0.2/0.7)等参数的协调搭配提升可读性

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)原始数据的叠加直方图")
$title
[1] "(a)原始数据的叠加直方图"

attr(,"class")
[1] "labels"
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("(b)标准化数据的叠加直方图")
$title
[1] "(b)标准化数据的叠加直方图"

attr(,"class")
[1] "labels"
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)+ # 绘制eruptions的直方图(上图)
   geom_label(aes(x=30,y=0.2),label="eruptions",color="red")+  # 添加标签
   geom_histogram(aes(x=waiting,y=-..density..),color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
   geom_label(aes(x=60,y=-0.1),label="waiting",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(a) 原始数据的镜像直方图")

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

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

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

  • 简洁直观美观

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=指标值,fill=指标)+
  geom_density(position="identity",color="grey60",alpha=0.5)+
  scale_fill_brewer(palette = "Set3")+
  facet_wrap(~指标,ncol=3,scale="free")+
  guides(fill="none")+
  theme(lefend.position=c(0.8,0.8),
        legend.background = element_rect(fill =  "grey90",colour = "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)+ # 绘制eruptions的直方图(上图)
   geom_label(aes(x=30,y=0.2),label="eruptions",color="red")+  # 添加标签
   geom_density(aes(x=waiting,y=-..density..),color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
   geom_label(aes(x=60,y=-0.1),label="waiting",color="blue")+  # 添加标签
   xlab("指标值")+ggtitle("(a) 原始数据的镜像核密度图")

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

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

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

  • 图形观察 分组核密度图:直观展示多个指标的分布形态,但指标多时曲线易重叠,难以区分。 分面核密度图:避免曲线重叠,每个指标独立展示,但指标多时分面过多会显得拥挤。 镜像核密度图:便于对比两个指标的分布形态,但只能展示两个指标,且分布差异大时不太直观。 代码编写 数据预处理是关键,如数据转换和标准化,为绘图提供合适的数据格式。 ggplot2功能强大,通过简单语法可绘制复杂图形,灵活调整颜色、位置等。 注释和清晰的代码结构有助于提高可读性和可维护性。

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

# Prepare data
df <- faithful %>%
  mutate(std.eruptions = scale(eruptions),
         std.waiting = scale(waiting))

# Define colors
my_colors <- brewer.pal(6, "Set2")[1:2]  # First two colors: "#66C2A5" "#FC8D62"

# 1. 原始数据箱线图
p_orig_box <- ggplot(df %>% pivot_longer(c(eruptions, waiting))) +
  geom_boxplot(aes(x = name, y = value, fill = name), 
               alpha = 0.7, width = 0.5, outlier.shape = NA) +
  stat_summary(aes(x = name, y = value), 
               fun = "mean", geom = "point", size = 3, color = "black") +
  scale_fill_manual(values = my_colors) +
  labs(title = "原始数据箱线图", x = "", y = "值") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "none")

# 2. 标准化数据箱线图
p_std_box <- ggplot(df %>% pivot_longer(c(std.eruptions, std.waiting))) +
  geom_boxplot(aes(x = name, y = value, fill = name), 
               alpha = 0.7, width = 0.5, outlier.shape = NA) +
  stat_summary(aes(x = name, y = value), 
               fun = "mean", geom = "point", size = 3, color = "black") +
  scale_fill_manual(values = my_colors, 
                    labels = c("eruptions", "waiting")) +
  labs(title = "标准化数据箱线图", x = "", y = "标准化值") +
  theme_minimal(base_size = 12) +
  theme(legend.position = "bottom")

# 显示箱线图
grid.arrange(p_orig_box, p_std_box, ncol = 2)

5.3 小提琴图代码

  • 通过d3r::d3_nest将数据框转化为层次数据“d3.js”作为绘图输入
# 数据处理
df<-data |>               # 删除不需要的变量
  gather(eruptions,waiting,key=指标,value=指标值)  |>  # 融合数据
  mutate(指标=fct_inorder(指标)) |> 
  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"))            # 设置图例字体大小

# 图(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 图形观察和代码编写的心得体会

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

5.5.1 图形观察

  • 小提琴图:结合了箱线图和核密度图的特点,既能展示数据的分布形态(通过小提琴的宽度),又能显示数据的统计信息(如箱线图中的中位数、四分位数)。通过对比原始数据和标准化数据的小提琴图,可以直观地看到数据分布的变化。
  • 均值点的添加:通过stat_summary添加均值点,能够更清晰地展示数据的集中趋势。
  • 离群点的处理:通过设置outlier.coloroutlier.size,可以更清晰地标识离群点,便于分析数据中的异常情况。

5.5.2 代码编写

  • 数据映射:通过aes函数指定xy的映射关系,同时利用fill参数区分不同指标。
  • 小提琴图与箱线图的结合geom_violin绘制小提琴图,geom_boxplot添加箱线图,两者结合提供了更丰富的信息。
  • 颜色与样式:通过scale_fill_brewer设置颜色方案,guides(fill="none")隐藏填充图例,使图形更简洁。
  • 组合图形:使用gridExtra::grid.arrange将多个图形组合在一起,便于对比分析。

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 威尔金森点图代码

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

# 标准化数据
df_std <- faithful %>% 
  mutate(across(c(eruptions, waiting), scale))

# 矩形热图
p1 <- ggplot(gather(df_std, key, value), aes(key, value)) +
  geom_dotplot(binaxis = "y", stackdir = "center", bins = 30, dotsize = 0.3) +
  labs(title = "矩形热图") +
  mytheme

# 极坐标热图
p2 <- ggplot(gather(df_std, key, value), aes(key, value)) +
  geom_dotplot(binaxis = "y", stackdir = "center", bins = 30, dotsize = 0.3) +
  coord_polar() +
  labs(title = "极坐标热图") +
  mytheme

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

6.3 蜂群图代码

library(ggbeeswarm)

# 基础蜂群图
p3 <- ggplot(gather(df_std, key, value), aes(key, value)) +
  geom_beeswarm(cex = 0.8, shape = 21, size = 0.8) +
  labs(title = "基础蜂群图") +
  mytheme

# 带箱线图蜂群图
p4 <- ggplot(gather(df_std, key, value), aes(key, value)) +
  geom_boxplot(width = 0.2, alpha = 0.5) +
  geom_beeswarm(cex = 0.8, shape = 21, size = 0.8) +
  labs(title = "带箱线图蜂群图") +
  mytheme

grid.arrange(p3, p4, ncol = 2)

6.4 云雨图代码

library(see)
library(ggdist)
library(ggplot2)

# 设置主题
mytheme <- theme_modern() +
  theme(legend.position = "none",
        plot.title = element_text(size = 14, hjust = 0.5))

# 纵向云雨图(简洁美观版)
ggplot(faithful, aes(x = "", y = scale(eruptions))) +
  stat_halfeye(fill = "#66C2A5", alpha = 0.7) +
  stat_dots(side = "left", fill = "#FC8D62", color = NA) +
  labs(title = "eruptions云雨图") +
  mytheme +
  coord_flip()

# 横向云雨图(简洁美观版)
ggplot(faithful, aes(y = "", x = scale(waiting))) +
  stat_halfeye(fill = "#FC8D62", alpha = 0.7) +
  stat_dots(side = "bottom", fill = "#66C2A5", color = NA) +
  labs(title = "waiting云雨图") +
  mytheme

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

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

6.6.1 图形观察

  • 矩形热图
    • 通过点的密集程度直观展示数据分布,适合观察数据的聚集区域。
    • 点图的堆积方向和密度可以反映变量的分布范围和集中趋势。
  • 极坐标热图
    • 将矩形热图转换为极坐标形式,视觉上更具吸引力。
    • 适合展示周期性或循环性数据,但可能不如矩形热图直观。
  • 基础蜂群图
    • 通过点的分布展示数据的离散程度,避免了点的重叠问题。
    • 适合展示分类变量和连续变量的关系。
  • 带箱线图蜂群图
    • 结合箱线图和蜂群图,既能展示数据的分布形态,又能提供统计信息(如中位数、四分位数)。
    • 适合详细分析数据的分布和异常值。
  • 云雨图
    • 结合了核密度图和点图,直观展示数据的分布和密度。
    • 适合展示单变量数据的分布,尤其是数据量较大时。

6.6.2 代码编写

  • 数据预处理
    • 使用mutatescale对数据进行标准化处理,便于后续绘图。
    • 使用gather将数据从宽格式转换为长格式,适应ggplot2的输入格式。
  • 图形绘制
    • 威尔金森点图:通过geom_dotplot绘制,调整binaxisstackdir等参数控制点的堆积方向和密度。
    • 蜂群图:使用ggbeeswarm包的geom_beeswarm绘制,避免点的重叠。
    • 云雨图:结合stat_halfeyestat_dots绘制,利用ggdist包实现核密度和点图的结合。
  • 图形美化
    • 使用theme_modern和自定义主题设置美化图形。
    • 使用coord_flip调整坐标轴方向,使图形更美观。
    • 通过fillalpha参数调整颜色和透明度,增强视觉效果。
  • 组合图形
    • 使用grid.arrange将多个图形组合在一起,便于对比分析。