首页
/ 使用ggplot2进行数据可视化设计:天气类型与自行车共享量的分布分析

使用ggplot2进行数据可视化设计:天气类型与自行车共享量的分布分析

2025-06-02 11:36:25作者:魏侃纯Zoe

前言

在数据可视化领域,ggplot2作为R语言中最强大的绘图系统之一,提供了丰富的图形语法和灵活的定制能力。本文基于rstudio-conf-2022中关于ggplot2图形设计的研讨会材料,重点讲解如何使用不同类型的图表展示伦敦自行车共享数据中不同天气条件下的使用量分布。

数据准备

首先我们需要导入并预处理数据:

# 导入伦敦自行车共享数据
bikes <- readr::read_csv("london-bikes-custom.csv", 
                        col_types = "Dcfffilllddddc")

# 将季节因子按顺序排列
bikes$season <- forcats::fct_inorder(bikes$season)

library(tidyverse)

基础箱线图分析

最简单的分布可视化方式是使用箱线图:

ggplot(bikes, aes(x = weather_type, y = count)) +
  geom_boxplot()

这个基础图表展示了不同天气类型下自行车使用量的分布情况,但存在两个问题:

  1. 天气类型标签重叠
  2. 图表缺乏必要的修饰

图表优化技巧

1. 解决标签重叠问题

有三种常用方法解决x轴标签重叠:

方法一:交换x和y轴

ggplot(bikes, aes(x = count, y = weather_type)) +
  geom_boxplot()

方法二:使用str_wrap自动换行

ggplot(bikes, aes(x = stringr::str_wrap(weather_type, 6), y = count)) +
  geom_boxplot()

2. 主题设置与美化

# 设置基础主题
theme_set(theme_minimal(
  base_size = 14,
  base_family = "Roboto Condensed"
))

# 自定义主题元素
theme_update(
  panel.grid.major.x = element_blank(),
  panel.grid.minor = element_blank(),
  plot.title.position = "plot"
)

# 添加标题和标签
ggplot(bikes, aes(x = stringr::str_wrap(weather_type, 6), y = count)) +
  geom_boxplot() +
  ggtitle("Reported bike shares by weather type")

高级可视化技术

1. 抖动散点图(Jitter Plot)

展示原始数据点的分布:

ggplot(bikes, aes(x = str_wrap(weather_type, 6), y = count)) +
  geom_jitter(alpha = 0.2) +
  ggtitle("Reported bike shares by weather type")

可以精确控制抖动参数:

geom_point(
  position = position_jitter(
    seed = 2022,  # 设置随机种子保证可重复性
    width = 0.2,  # 水平抖动范围
    height = 0    # 垂直不抖动
  ),
  alpha = 0.2
)

2. 箱线图与散点图组合

结合箱线图的统计信息和散点图的原始数据展示:

ggplot(bikes, aes(x = str_wrap(weather_type, 6), y = count)) +
  geom_boxplot(outlier.shape = NA) +  # 隐藏箱线图的异常值点
  geom_jitter(alpha = 0.2) +
  ggtitle("Reported bike shares by weather type")

3. 按中位数排序

ggplot(bikes, aes(
  x = forcats::fct_reorder(str_wrap(weather_type, 6), -count),
  y = count)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(alpha = 0.2)

其他分布可视化方法

1. 蜂群图(Beeswarm Plot)

使用ggbeeswarm包可以创建更有序的点分布:

g + 
  geom_boxplot(outlier.shape = NA) +
  ggbeeswarm::geom_beeswarm(
    size = 0.3,
    alpha = 0.2,
    cex = 0.6  # 控制点间距
  )

2. 小提琴图(Violin Plot)

展示分布的密度估计:

g +
  geom_violin(
    scale = "count",  # 按样本量缩放宽度
    draw_quantiles = c(0.5),  # 标记中位数
    fill = "grey80"
  )

3. 雨云图(Raincloud Plot)

结合密度图、箱线图和原始数据点的综合展示:

g +
  ggdist::stat_halfeye(  # 半密度图
    aes(thickness = stat(f*n)),  # 按频数调整厚度
    width = 0.5,
    position = position_nudge(x = 0.2)
  ) +
  geom_boxplot(width = 0.3) +
  geom_jitter(width = 0.1, size = 0.5, alpha = 0.1)

图表保存

最后将图表保存为高质量矢量图:

ggsave("bike_shares_weather.pdf", 
       width = 5, height = 6.5, device = cairo_pdf)

总结

本文展示了使用ggplot2可视化分布数据的多种方法,从基础的箱线图到高级的雨云图,每种图表都有其适用场景:

  1. 箱线图:快速了解分布的关键统计量
  2. 抖动散点图:展示所有数据点的分布
  3. 蜂群图:有序展示数据点避免重叠
  4. 小提琴图:直观显示数据密度
  5. 雨云图:综合展示密度、统计量和原始数据

通过灵活运用这些技术,可以更全面、有效地展示数据分布特征,为数据分析提供更丰富的视角。

登录后查看全文
热门项目推荐