You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggplot为堆叠Dotplot中密集点添加堆叠式标签?

为Dotplot添加堆叠式标签的实现方案

核心思路

geom_dotplot本身不会输出每个点的坐标信息,要给每个点加标签,需先提取它计算好的堆叠位置,关联原始数据的标签(汽车名称),最后用文本图层实现堆叠显示。

步骤1:提取Dotplot的点坐标

先绘制基础图,通过ggplot_build提取图层的布局数据,这里包含了每个点的x和堆叠后的y坐标:

# 基础Dotplot
base_plot <- ggplot(mtcars, aes(x = mpg)) +
  geom_dotplot(binwidth = .4, stackdir = "centerwhole") +
  scale_y_continuous(NULL, breaks = NULL)

# 提取每个点的坐标数据
plot_coords <- ggplot_build(base_plot)$data[[1]]

# 关联汽车名称:按mpg排序后匹配点的顺序
mtcars_sorted <- mtcars[order(mtcars$mpg), ]
plot_coords$car_name <- rownames(mtcars_sorted)

步骤2:添加堆叠式标签

直接用提取的坐标添加文本,对于聚集点,通过分组计算y偏移量让标签垂直堆叠:

library(dplyr)

# 对同一mpg的点,计算标签的y轴偏移量,实现堆叠
plot_coords <- plot_coords %>%
  group_by(x) %>%
  mutate(label_y = y + seq(0.1, n()*0.1, by = 0.1)) %>%
  ungroup()

# 绘制带标签的Dotplot
ggplot(mtcars, aes(x = mpg)) +
  geom_dotplot(binwidth = .4, stackdir = "centerwhole") +
  geom_text(data = plot_coords, aes(x = x, y = label_y, label = car_name),
            size = 3, hjust = 0.5, color = "darkred") +
  scale_y_continuous(NULL, breaks = NULL) +
  labs(x = "每加仑英里数(mpg)")

可选优化:自动避免标签重叠

如果点的数量很多,手动调整偏移量不够灵活,可以用ggrepel包的geom_text_repel自动调整标签位置,同时保持堆叠方向:

library(ggrepel)

ggplot(mtcars, aes(x = mpg)) +
  geom_dotplot(binwidth = .4, stackdir = "centerwhole") +
  geom_text_repel(data = plot_coords, aes(x = x, y = y, label = car_name),
                  size = 3, direction = "y", color = "darkblue") +
  scale_y_continuous(NULL, breaks = NULL) +
  labs(x = "每加仑英里数(mpg)")

内容的提问来源于stack exchange,提问作者DavidWebb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:06:26