在 R 中使用 ggplot2 进行图形可视化

面向 SAS 用户的 R

Melinda Higgins, PhD

Research Professor/Senior Biostatistician Emory University

ggplot2 包

ggplot2 六边形贴纸标识

  • ggplot2 是 R 的强大绘图包
  • ggplot 中的 "GG" 指的是 "grammar of graphics"
  • ggplot2 采用分层绘图方式
  • 在基础图层上添加一个或多个几何对象
面向 SAS 用户的 R

图层——基础图层

# Create plot for x=sex and y=diameter
ggplot(data = abalone, aes(sex, diameter))
  • ggplot() 定义基础图层
  • 设置 data = abalone
  • aes 设为 sexdiameter

  • 目前还没有添加几何对象

  • x 轴已就绪用于 sex
  • y 轴已就绪用于 diameter
  • 网格已铺好

ggplot2 图形环境,尚无箱线图

面向 SAS 用户的 R

图层——添加箱线图几何对象

# Add boxplot geometric object or geom
ggplot(data = abalone,
       aes(sex, diameter)) +
  geom_boxplot()
  • 使用加号 + 添加图层
  • 添加箱线图 geom_boxplot()

  • 得到一组箱线图

  • 按性别展示鲍鱼直径
  • F 雌性,I 幼体,M 雄性

ggplot2 已添加箱线图

面向 SAS 用户的 R

图层——添加主题

# Add black white theme
ggplot(data = abalone,
       aes(sex, diameter)) +
  geom_boxplot() +
  theme_bw()
  • theme_bw() 添加主题图层
  • 去除灰色背景
  • 在图外画黑色边框

ggplot2 箱线图已添加黑白主题

面向 SAS 用户的 R

将箱线图改为小提琴图

# Change to geom_violin()
ggplot(data = abalone,
       aes(sex, diameter)) +
  geom_violin() +
  theme_bw()
  • geom_violin 替换 geom_boxplot
  • 生成类似小提琴的形状
  • 反映数据密度分布
  • 小改动即可得到新图

ggplot2 小提琴图

面向 SAS 用户的 R

单变量直方图

# Make histogram of shuckedWeight
ggplot(abalone, aes(shuckedWeight)) +
  geom_histogram()
  • 为单个变量绘制直方图
  • 一个变量 = 一个美学映射
  • 添加 geom_histogram()
  • aes() 设为 shuckedWeight
  • 默认配色需调整

ggplot2 直方图全黑

面向 SAS 用户的 R

直方图添加配色

# Make lines black and fill light blue
ggplot(abalone, aes(shuckedWeight)) +
  geom_histogram(color = "black",
                 fill = "lightblue")
  • 修改图形参数
  • 设置区间边线的 color
  • 设置区间填充的 fill 颜色
  • 选项写在函数的 ()
  • 直方图更美观了

ggplot2 蓝色柱,黑色边线的直方图

面向 SAS 用户的 R

直方图添加标题与轴标签

# Add x, y axis labels and title
ggplot(abalone, aes(shuckedWeight)) +
  geom_histogram(color = "black",
                 fill = "lightblue") +
  xlab("Shucked Weight") +
  ylab("Frequency Counts") +
  ggtitle("Shucked Weights Histogram")
  • 为坐标轴和标题添加更佳标签
  • 坐标轴用 xlab()ylab()
  • 标题用 ggtitle()
  • 这幅图已可发布!

ggplot2 直方图已添加轴标签和标题

面向 SAS 用户的 R

绘制散点图

# Make scatterplot with geom_point()
ggplot(abalone,
       aes(rings, shellWeight)) +
  geom_point()
  • 散点图的 aes 需要两个变量
  • geom_point() 添加点
  • 绘制按环数的壳重散点图

ggplot2 按环数的壳重散点图

面向 SAS 用户的 R

散点图添加平滑拟合线

# Add smoothed fit line
ggplot(abalone,
       aes(rings, shellWeight)) +
  geom_point() +
  geom_smooth()
  • 在散点图上添加 geom_smooth() 拟合线
  • 自带阴影置信区间

ggplot2 散点图已添加平滑拟合线

面向 SAS 用户的 R

按另一变量创建分面面板

# Add panels using facet_wrap()
ggplot(abalone,
       aes(rings, shellWeight)) +
  geom_point() +
  geom_smooth() +
  facet_wrap(vars(sex))
  • 在散点图上再加一层
  • 为每个鲍鱼性别创建分面面板
  • 添加 facet_wrap() 图层
  • vars(sex) 指定分面变量

ggplot2 按性别的三面板散点图

面向 SAS 用户的 R

后续内容

  • 第 1 章以图形入门作结
    • ggplot2 绘图基础
    • 按性别可视化鲍鱼测量值
  • 第 2 章讲数据整形
    • 清理鲍鱼数据集
  • 第 3 章讲数据探索
    • 描述统计、相关性与比较检验
  • 第 4 章讲建模与结果展示
    • 用测量值预测鲍鱼年龄
    • 按性别比较模型
面向 SAS 用户的 R

让我们为鲍鱼做些图吧

面向 SAS 用户的 R

Preparing Video For Download...