tidyverse-数据可视化 - 图形的分层语法
1. ggplot2 的基本概念
ggplot2 是一个基于 R 的数据可视化包,它基于“图形的分层语法”(grammar of graphics)。这意味着你可以通过组合不同的图层和组件来构建复杂的图形。
核心组件:
- 数据(Data):你要可视化的数据集。
- 美学映射(Aesthetics):将数据变量映射到图形的视觉属性(如颜色、形状、大小等)。
- 几何对象(Geometric Objects, Geoms):决定数据如何显示(如点、线、柱状图等)。
- 统计变换(Statistical Transformations, Stats):对数据进行计算或转换(如计数、拟合模型等)。
- 位置调整(Position Adjustments):调整几何对象的位置(如堆叠、并排、抖动等)。
- 坐标系(Coordinate Systems):决定数据在图形中的位置和比例(如笛卡尔坐标系、极坐标系等)。
- 刻面(Facets):将数据拆分为多个子图,便于比较不同子集。
- 主题(Theme):控制图形的整体外观(如字体、颜色、背景等)。
2. 美学映射(Aesthetics)
美学映射是将数据变量映射到图形的视觉属性。例如,你可以将一个数值变量映射到 x 轴,另一个数值变量映射到 y 轴,还可以将分类变量映射到颜色或形状。
示例代码:
library(ggplot2)# 数据集 mpg
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point() # 使用颜色美学映射
解释:
ggplot(mpg, aes(x = displ, y = hwy, color = class))
:mpg
是数据集。aes()
定义了美学映射:displ
映射到 x 轴,hwy
映射到 y 轴,class
映射到颜色。
geom_point()
:添加点几何对象,绘制散点图。
3. 几何对象(Geometric Objects)
几何对象决定了数据如何显示。不同的几何对象可以揭示数据的不同特征。
示例代码:
# 散点图
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() # 点几何对象# 平滑曲线图
ggplot(mpg, aes(x = displ, y = hwy)) + geom_smooth() # 平滑曲线几何对象
解释:
geom_point()
:绘制散点图。geom_smooth()
:绘制平滑曲线,用于显示数据的趋势。
4. 刻面(Facets)
刻面用于将数据拆分为多个子图,便于比较不同子集。
示例代码:
# 根据 cyl 分面
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() +facet_wrap(~ cyl) # 单变量分面# 根据 drv 和 cyl 分面
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() +facet_grid(drv ~ cyl) # 双变量分面
解释:
facet_wrap(~ cyl)
:根据cyl
变量将数据拆分为多个子图。facet_grid(drv ~ cyl)
:根据drv
和cyl
的组合将数据拆分为多个子图。
5. 统计变换(Statistical Transformations)
统计变换用于对数据进行计算或转换。例如,geom_bar()
默认使用 stat_count
计算每个类别的计数。
示例代码:
# 条形图
ggplot(diamonds, aes(x = cut)) + geom_bar() # 默认使用 stat_count# 自定义统计变换
ggplot(diamonds, aes(x = cut, y = after_stat(prop), group = 1)) + geom_bar() # 显示比例而不是计数
解释:
geom_bar()
:默认使用stat_count
计算每个类别的计数。after_stat(prop)
:使用统计变换计算比例。
6. 位置调整(Position Adjustments)
位置调整用于控制几何对象的位置,避免重叠或更好地展示数据。
示例代码:
# 堆叠条形图
ggplot(mpg, aes(x = drv, fill = class)) + geom_bar() # 默认堆叠# 并排条形图
ggplot(mpg, aes(x = drv, fill = class)) + geom_bar(position = "dodge") # 并排显示# 抖动散点图
ggplot(mpg, aes(x = displ, y = hwy)) + geom_jitter() # 避免点重叠
解释:
position = "dodge"
:将重叠的对象并排放置。geom_jitter()
:在散点图中添加随机噪声,避免数据点重叠。
7. 坐标系(Coordinate Systems)
坐标系决定了数据在图形中的位置和比例。
示例代码:
# 极坐标
ggplot(diamonds, aes(x = clarity, fill = clarity)) + geom_bar() +coord_polar() # 使用极坐标
解释:
coord_polar()
:将数据转换为极坐标,可用于绘制饼图或 Coxcomb 图。
8. 练习
现在,让我们通过一些练习来巩固这些知识!
练习 1:创建一个散点图,将 mpg
数据集中的 displ
映射到 x 轴,hwy
映射到 y 轴,并将 class
映射到颜色。
ggplot(mpg, aes(x = displ, y = hwy, color = class)) + geom_point()
练习 2:创建一个条形图,显示 diamonds
数据集中不同 cut
的数量。
ggplot(diamonds, aes(x = cut)) + geom_bar()
练习 3:根据 drv
和 cyl
分面,创建一个散点图。
ggplot(mpg, aes(x = displ, y = hwy)) + geom_point() +facet_grid(drv ~ cyl)
练习 4:创建一个平滑曲线图,并将 drv
映射到线型。
ggplot(mpg, aes(x = displ, y = hwy, linetype = drv)) + geom_smooth()
练习 5:创建一个饼图,显示 diamonds
数据集中不同 clarity
的比例。
ggplot(diamonds, aes(x = "", fill = clarity)) + geom_bar(width = 1) +coord_polar(theta = "y")
总结
通过这些示例和练习,你应该能够理解 ggplot2 的基本概念,并能够创建各种类型的图形。如果你有任何问题,随时问我!