= faithful
data datatable(data,rownames = FALSE)
第四章 数据分布可视化
1 解释原始数据
faithful
是R语言中自带的一个经典数据集,它记录了美国黄石国家公园老忠实间歇泉(Old Faithful geyser)的喷发数据。这个数据集经常被用于统计教学和数据分析示例。faithful
数据集包含两个变量,共有272个观测值。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) # 用于计算偏度系数和峰度系数
<- data
df # 作初始直方图,纵轴默认为频数
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.6,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,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=4.2,label="中位数",size=3,color="red3") # 添加注释文本
2.3 图形观察和代码编写的心得体会
eruptions
的直方图呈双峰分布,核密度曲线也印证了这一点,表明喷发时间可能受两种不同机制影响。均值线(红色虚线)和中位数点(黄色)接近,但偏度系数显示分布略有右偏,峰度系数表明数据比正态分布更平缓(低峰态)。ggplot2
采用图层叠加逻辑,依次用geom_histogram
(直方图)、geom_density
(密度曲线)、geom_vline
(均值线)等逐步增强可视化信息。通过annotate
动态计算并标注统计量(如skewness
、mean
),使图形更具解释性,代码也易于复用。
3 叠加直方图和镜像直方图
3.1 绘图要求
绘制
eruptions
和waiting
两个变量的叠加直方图和镜像直方图,使用预设主题:mytheme。将数据转化为长型数据再作叠加直方图,利用
scale_fill_brewer()
将叠加直方图配色方案改为set3
。镜像直方图中
eruptions
在正方向,waiting
在负方向,直方数bins=30
,并添加文字标签作标签。两种图都需要针对原始数据作图和标准标准化数据作图,可以使用
scale()
函数对变量标准化,分类标准化可以使用plyr::ddply()
函数。
3.2 叠加直方图代码
<- data |>
df gather(eruptions,waiting,key=指标,value=指标值) %>% # 融合数据
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值并返回数据框
<-ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
p1geom_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) 原始数据叠加直方图")
<-ggplot(df)+aes(x=标准化值,y=..density..,fill=指标)+
p2geom_histogram(position="identity",color="gray60",alpha=0.5)+
scale_fill_brewer(palette = "Set3")+
theme(legend.position=c(0.5,0.9),# 设置图例位置
legend.background=element_rect(fill="grey90",color="grey"))+
# 设置图例背景色和边框颜色
ggtitle("(b) 标准化数据叠加直方图")
::grid.arrange(p1,p2,ncol=2) # 组合图形 gridExtra
3.3 镜像直方图代码
<- data |>
df mutate(
std.eruptions=scale(eruptions),
std.waiting=scale(waiting)
)
<-ggplot(df)+aes(x=x)+
p1geom_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..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
geom_label(aes(x=60,y=-0.1),label="waiting",color="blue")+ # 添加标签
xlab("指标值")+ggtitle("(a) 原始数据镜像直方图")
<-ggplot(df)+aes(x=x)+
p2geom_histogram(aes(x=std.eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制eruptions的直方图(上图)
geom_label(aes(x=-0.5,y=0.4),label="eruptions",color="red")+ # 添加标签
geom_histogram(aes(x=std.waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
geom_label(aes(x=-0.5,y=-0.4),label="waiting",color="blue")+ # 添加标签
xlab("指标值")+ggtitle("(b) 标准化数据镜像直方图")
::grid.arrange(p1,p2,ncol=2) # 组合图形 gridExtra
3.4 图形观察和代码编写的心得体会
叠加直方图:eruptions
和 waiting
的原始直方图(a)显示两者量纲差异大,waiting
的数值范围明显更广,直接叠加会掩盖分布细节,标准化后(b)的直方图消除了量纲影响,能清晰对比两变量的分布形态,可见两者均呈双峰结构,但峰位置和宽度不同。使用 gather
+ ddply
组合实现数据融合与分组标准化,避免手动分步计算,代码更简洁。
镜像直方图:通过正负密度值的镜像对称布局,原始数据直方图(a)直观暴露了eruptions
(红)和waiting
(蓝)的量纲差异,而标准化后(b)则聚焦分布形态相似性(均呈双峰)。标准化处理消除了量纲干扰,使两变量的分布宽度和峰值位置可比性增强,凸显waiting
的右偏更明显。使用mutate(scale())
直接生成标准化列,避免冗长的数据重塑,代码更易读。通过y=..density..
和y=-..density..
实现上下镜像,配合标签定位(geom_label
)增强可读性,体现ggplot2
的灵活映射能力。
4 核密度图
4.1 绘图要求
绘制eruptions和 waiting两个变量的分组核密度图、分面核密度图和镜像核密度图。
分组核密度图,采用
geom_density(position="identity")
。分面核密度图,采用
geom_density()+facet_wrap(~xx,scale="free")
。镜像核密度图中
eruptions
在正方向,waiting
在负方向,直方数bins=30
,并添加文字标签作标签。分组核密度图和镜像核密度图需要针对原始数据作图和标准标准化数据作图。
4.2 分组核密度图
<- data |>
df gather(eruptions,waiting,key=指标,value=指标值) %>% # 融合数据
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值并返回数据框
<-ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
p1geom_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) 原始数据叠加直方图")
<-ggplot(df)+aes(x=标准化值,y=..density..,fill=指标)+
p2geom_density(position="identity",color="gray60",alpha=0.5)+
scale_fill_brewer(palette = "Set3")+
theme(legend.position=c(0.4,0.8),# 设置图例位置
legend.background=element_rect(fill="grey90",color="grey"))+
# 设置图例背景色和边框颜色
ggtitle("(b) 标准化数据叠加直方图")
::grid.arrange(p1,p2,ncol=2) # 组合图形 gridExtra
4.3 分面核密度图
ggplot(df)+aes(x=指标值,y=..density..,fill=指标)+
geom_density(position="identity",color="gray60",alpha=0.5)+
scale_fill_brewer(palette = "Set3")+
guides(fill="none")+
facet_wrap(~指标,ncol = 2,scale="free")
theme(legend.position=c(0.8,0.8),# 设置图例位置
legend.background=element_rect(fill="grey90",color="grey"))
List of 3
$ legend.background :List of 5
..$ fill : chr "grey90"
..$ colour : chr "grey"
..$ linewidth : NULL
..$ linetype : NULL
..$ inherit.blank: logi FALSE
..- attr(*, "class")= chr [1:2] "element_rect" "element"
$ legend.position : chr "inside"
$ legend.position.inside: num [1:2] 0.8 0.8
- attr(*, "class")= chr [1:2] "theme" "gg"
- attr(*, "complete")= logi FALSE
- attr(*, "validate")= logi TRUE
4.4 镜像核密度图
<- data |>
df mutate(
std.eruptions=scale(eruptions),
std.waiting=scale(waiting)
)
<-ggplot(df)+aes(x=x)+
p1geom_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..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
geom_label(aes(x=60,y=-0.1),label="waiting",color="blue")+ # 添加标签
xlab("指标值")+ggtitle("(a) 原始数据镜像核密度")
<-ggplot(df)+aes(x=x)+
p2geom_density(aes(x=std.eruptions,y=..density..),bins=30,color="grey50",fill="red",alpha=0.3)+ # 绘制eruptions的直方图(上图)
geom_label(aes(x=-0.5,y=0.3),label="eruptions",color="red")+ # 添加标签
geom_density(aes(x=std.waiting,y=-..density..),bins=30,color="grey50",fill="blue",alpha=0.3)+ # 绘制waiting的直方图(下图)
geom_label(aes(x=-0.5,y=-0.3),label="waiting",color="blue")+ # 添加标签
xlab("指标值")+ggtitle("(b) 标准化数据镜像核密度")
::grid.arrange(p1,p2,ncol=2) # 组合图形 gridExtra
4.5 图形观察和代码编写的心得体会
叠加核密度图:通过透明度和颜色叠加展示两个变量的分布重叠情况,直接比较形状相似性,但量纲差异大时较难观察(如原始数据图a)分面核密度图:将两个变量分开绘制并自由缩放坐标轴(
scale="free"
),能清晰展示各自分布特征,尤其适合量纲差异大的情况。镜像核密度图:利用正负y轴镜像对称布局,既保留分布形状对比,又通过空间分离解决量纲干扰问题,标准化后(图b)的对比效果更显著只需将
geom_histogram
替换为geom_density
即可从直方图切换为核密度图,保持其他美学映射(fill/color/alpha)不变。facet_wrap
实现空间分割,而镜像图通过y轴变换实现叠加对比,二者分别适用于不同分析场景。
5 箱线图和小提琴图
5.1 绘图要求
根据实际数据和标准化后的数据绘制
eruptions
和waiting
两个变量的箱线图geom_boxplot
和小提琴图geom_violin
。采用
stat_summary(fun="mean",geom="point")
在箱线图和均值图中要添加均值点。小提琴图中要加入点图和箱线图
采用调色板前两种颜色,
brewer.pal(6,"Set2")[1:2]
,作为箱体填充颜色。
"#66C2A5" "#FC8D62" "#8DA0CB" "#E78AC3" "#A6D854" "#FFD92F"
5.2 箱线图代码
<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
mythemeaxis.title=element_text(size=10), # 设置坐标轴标签字体大小
axis.text=element_text(size=9), # 设置坐标轴刻度字体大小
legend.text=element_text(size="8")) # 设置图例字体大小
<-data |>
dfgather(everything(),key=指标,value=指标值) |>
mutate(指标=fct_inorder(指标))
<-RColorBrewer::brewer.pal(6,"Set2")[1:2] # 设置离散型调色板
palette<-ggplot(df,aes(x=指标,y=指标值))+
p1geom_boxplot(fill=palette)+ # 绘制箱线图并设置填充颜色
stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
ggtitle("(a) 原始数据箱线图")
<-data |> #标准化后
dfgather(everything(),key=指标,value=指标值) |>
mutate(指标=fct_inorder(指标)) |>
ddply("指标",transform,标准化值=scale(指标值))
<-ggplot(df,aes(x=指标,y=标准化值))+
p2geom_boxplot(fill=palette)+ # 绘制箱线图并设置填充颜色
stat_summary(fun="mean",geom="point",shape=21,size=2.5,fill="white")+
ggtitle("(b) 标准化数据箱线图")
::grid.arrange(p1,p2,ncol=2) # 组合图形 gridExtra
5.3 小提琴图代码
- 通过
d3r::d3_nest
将数据框转化为层次数据“d3.js”作为绘图输入
# 数据处理
<-data |>
dfgather(everything(),key=指标,value=指标值) |> # 融合数据
mutate(指标=fct_inorder(指标)) |>
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值
# 设置图形主题
<-theme(plot.title=element_text(size="11"), # 设置主标题字体大小
mythemeaxis.title=element_text(size=10), # 设置坐标轴标签字体大小
axis.text=element_text(size=9), # 设置坐标轴刻度字体大小
legend.text=element_text(size="8")) # 设置图例字体大小
# 图(a)原始数据小提琴图
<-ggplot(df,aes(x=指标,y=指标值,fill=指标))+
p1geom_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)数据标准化后的小提琴图
<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
p2geom_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) 标准化小提琴图")
::grid.arrange(p1,p2,ncol=2) # 组合图形p1和p2 gridExtra
5.4 图形观察和代码编写的心得体会
箱线图:直接展示数据分布的五数概括(最小值、Q1、中位数、Q3、最大值)和离群点,标准化前后对比明显(图b消除量纲差异),但无法展示分布密度。小提琴图:结合核密度估计(展示数据分布形状)和箱线图(展示统计量),原始数据图(a)能同时看到双峰分布特征和统计量,标准化图(b)更侧重比较分布形态相似性
两种图形均采用
gather
+mutate
+ddply
的标准化数据处理流程,保证代码可复用性。小提琴图通过geom_violin
+geom_boxplot
+stat_summary
多层叠加,既展示分布形状又强调关键统计量(如均值/四分位数)。采用调色板前两种颜色,brewer.pal(6,"Set2")[1:2]
,作为箱体填充颜色。
6 威尔金森点图、蜂群图和云雨图
6.1 绘图要求
绘制
eruptions
和waiting
两个变量的威尔金森点图、蜂群图和云雨图。三种图形均采用标准化数据作图
威尔金森点图采用
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 威尔金森点图代码
分别作矩形热图和极坐标热图
<-theme_bw()+theme(legend.position="none")
mytheme
<- data |>
df gather(everything(),key=指标,value=指标值) |> # 选择变量并转化成长格式
mutate(指标=fct_inorder(指标)) |>
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值
# 绘制图形
<-theme_bw()+theme(legend.position="none")
mytheme<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))
p<-p+geom_dotplot(binaxis="y",bins=30,,stackdir="center",dotsize = 0.3)+ # 绘制点图
p1+ggtitle("(a) 居中堆叠")
mytheme
<-p+geom_dotplot(binaxis="y",bins=30,dotsize = 0.3)+ # 绘制点图
p2+ggtitle("(b) 向上堆叠")
mytheme
::grid.arrange(p1,p2,ncol=2) # 按2列组合图形 gridExtra
6.3 蜂群图代码
<-theme_bw()+theme(legend.position="none")
mytheme
library(ggbeeswarm)
# 处理数据
<-data |>
dfgather(everything(),key=指标,value=指标值) |> # 将数据转化成长格式
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值
# 图(a)2项指标的蜂群图
<-theme_bw()+theme(legend.position="none")
mytheme<-ggplot(df,aes(x=指标,y=标准化值))
p<-p+geom_beeswarm(cex=0.8,shape=21,fill="black",size=0.8,aes(color=指标))+# 设置蜂群的宽度、点的形状、大小和填充颜色
p1+ggtitle("(a) 蜂群图")
mytheme
# 图(b)箱线图+蜂群图
<-p+geom_boxplot(size=0.5,outlier.size=0.8,aes(color=指标))+
p2geom_beeswarm(shape=21,cex=0.8,size=0.8,aes(color=指标))+
+ggtitle("(b) 箱线图+蜂群图")
mytheme
::grid.arrange(p1,p2,ncol=2) gridExtra
6.4 云雨图代码
library(see) # 提供主题函数theme_modern
<-theme_modern()+
mythemetheme(legend.position="none",
plot.title=element_text(size=14,hjust=0.5)) # 调整标题位置
# 处理数据
<-data |>
dfgather(everything(),key=指标,value=指标值) |> # 将数据转化成长格式
ddply("指标",transform,标准化值=scale(指标值)) # 计算标准化值
<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
p1geom_violindot(dots_size=0.7,binwidth=0.07)+ # 绘制云雨图并设置点的大小和箱宽
+ggtitle("(a) 垂直排列(默认)")
mytheme
<-ggplot(df,aes(x=指标,y=标准化值,fill=指标))+
p2geom_violindot(dots_size=0.7,binwidth=0.06)+
coord_flip()+mytheme+ggtitle("(b) 水平排列")
::grid.arrange(p1,p2,ncol=2) # 按2列组合图形p1和p2 gridExtra
6.5 图形观察和代码编写的心得体会
威尔金森点图:通过点阵堆叠方式(居中/向上)直观展示数据分布密度,适合小样本数据分布观察,但大数据量时易重叠。蜂群图:采用智能防重叠算法展示所有数据点,保持分布形状的同时避免重叠,结合箱线图(图b)可同时查看统计量和原始数据分布。云雨图:创新性整合小提琴图(分布形状)和点图(原始数据),垂直/水平布局灵活,提供最丰富的分布信息(密度、离散度、数据点)
三种图形均采用
gather()+ddply(scale())
标准化流程,体现”整洁数据”理念。通过ggbeeswarm
和see
包扩展ggplot2基础功能,快速实现专业级可视化效果(如自动避让算法、复合图形)