首页
/ 使用ggplot2创建圆形棒棒糖图:RStudio Conf 2022数据可视化教程

使用ggplot2创建圆形棒棒糖图:RStudio Conf 2022数据可视化教程

2025-06-02 21:15:34作者:秋阔奎Evelyn

引言

在数据可视化领域,ggplot2是R语言中最强大的绘图系统之一。本文将基于RStudio Conf 2022中关于ggplot2图形设计的教程,详细介绍如何创建精美的圆形棒棒糖图(lollipop plot),用于展示伦敦自行车共享数据在不同季节的使用情况。

数据准备

首先我们需要准备和预处理数据:

library(tidyverse)

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

# 处理季节因子,确保按顺序排列
bikes$season <- stringr::str_to_title(bikes$season)
bikes$season <- forcats::fct_inorder(bikes$season)

# 设置默认主题
theme_set(theme_light(base_size = 14, base_family = "Roboto Condensed"))

基础棒棒糖图

棒棒糖图结合了点图和线图的特点,适合展示分类变量的数值比较。我们先创建基本的笛卡尔坐标系下的棒棒糖图:

# 方法1:预先计算总和
bikes %>%
  group_by(season) %>%
  summarize(count = sum(count)) %>%
  ggplot(aes(x = season, y = count)) +
  geom_point(size = 3) +
  geom_linerange(aes(ymin = 0, ymax = count))

# 方法2:使用stat_summary动态计算
ggplot(bikes, aes(x = season, y = count)) +
  stat_summary(geom = "point", fun = "sum", size = 3) +
  stat_summary(geom = "linerange", ymin = 0, fun.max = function(y) sum(y))

转换为极坐标系

将笛卡尔坐标系转换为极坐标系可以创建环形图效果:

bikes %>%
  group_by(season) %>%
  summarize(count = sum(count)) %>%
  ggplot(aes(x = season, y = count)) +
  geom_point(size = 3) +
  geom_linerange(aes(ymin = 0, ymax = count)) +
  coord_polar(theta = "y")  # 关键转换

优化圆形布局

转换为极坐标后,我们需要调整几个关键参数:

# 调整坐标轴范围和间距
+ scale_x_discrete(expand = c(.5, .5)) +
  scale_y_continuous(limits = c(0, 7.5*10^6))

# 移除所有主题元素
+ theme_void()

# 调整边距使图形居中
+ theme(plot.margin = margin(rep(-100, 4)))

添加标签和基线

为了增强图表的可读性,我们需要添加季节标签和基准线:

# 添加季节标签
geom_text(
  aes(label = season, y = 0),
  family = "Cabinet Grotesk", size = 4.5,
  fontface = "bold", hjust = 1.15
)

# 添加基准线(推荐方法)
annotate(
  geom = "linerange",
  xmin = .7, xmax = 4.3, y = 0
)

完整解决方案

结合所有优化步骤,最终代码如下:

ggplot(bikes, aes(x = as.numeric(season), y = count)) +
  stat_summary(geom = "point", fun = "sum", size = 3) +
  stat_summary(geom = "linerange", ymin = 0, fun.max = function(y) sum(y)) +
  stat_summary(
    geom = "text",
    aes(label = season, y = 0),
    family = "Cabinet Grotesk", size = 4.5,
    fontface = "bold", hjust = 1.15
  ) +
  annotate(geom = "linerange", xmin = .7, xmax = 4.3, y = 0) +
  coord_polar(theta = "y") +
  scale_x_discrete(expand = c(.5, .5)) +
  scale_y_continuous(limits = c(0, 7.5*10^6)) +
  theme_void() +
  theme(plot.margin = margin(rep(-100, 4)))

设计要点总结

  1. 数据聚合:使用group_by()summarize()stat_summary()计算季节总和
  2. 极坐标转换coord_polar()将条形图转换为环形图
  3. 标签定位:通过调整y值和hjust参数精确控制标签位置
  4. 视觉优化:使用theme_void()简化背景,调整边距使图形居中
  5. 基准线:使用annotate()添加自定义参考线

这种圆形棒棒糖图不仅美观,而且能有效展示周期性数据(如季节变化)的模式,是数据可视化工具箱中的有力补充。

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