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

geom_dotplot与geom_text_repel能否搭配实现带标签的点图?

密集点图geom_text_repel引线错位解决方案

错误原因

geom_dotplot会自动对同组、同y值的点做水平堆叠偏移,而geom_text_repel默认调用原始数据集的x/y坐标定位文本,没有匹配每个点堆叠后的实际位置,因此引线无法对准对应点位。

修正代码

首先提前计算每个点堆叠后的实际x坐标,再传入geom_text_repel即可:

# 加载依赖包
library(ggplot2)
library(ggrepel)
library(dplyr)

# 原始数据
df <- data.frame(
  name = c("A1","A2","B1","B2","B3"),
  value = c(1,2,2,2,2),
  group = c("A","A","B","B","B")
)

# 预计算每个点的堆叠水平偏移,匹配geom_dotplot的堆叠逻辑
df <- df %>% 
  group_by(group, value) %>% 
  mutate(
    dot_id = row_number(),
    n = n(),
    # 0.12为适配dotsize=1的偏移系数,修改dotsize时需要同步调整
    x_offset = (dot_id - (n+1)/2) * 0.12,
    x_pos = as.numeric(factor(group)) + x_offset
  )

# 绘图
ggplot(df, aes(x = group, y = value, label = name)) +
  geom_dotplot(
    binaxis = 'y', 
    stackdir = 'center', 
    dotsize = 1
  ) +
  geom_text_repel(
    aes(x = x_pos, segment.color = "red"),
    box.padding = 1,
    max.overlaps = 10,
    # 可选:强制标签仅垂直方向排布,避免引线杂乱
    direction = "y"
  ) +
  # 移除segment.color的冗余图例
  guides(segment.color = "none")

参数调整说明

  • 偏移计算的0.12系数需要和dotsize参数适配:dotsize越大,系数也要对应调大,保证文本定位和点的堆叠位置完全对齐
  • 若不需要标签左右分布,保留direction = "y"参数即可得到更整齐的引线效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:57:03