You need to enable JavaScript to run this app. 如何为ggplot2绘制的beeswarm图添加指向对应散点的标签?
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggplot2绘制的beeswarm图添加指向对应散点的标签?

问题根因

你使用的geom_quasirandom会自动在分类轴方向给每个点添加随机偏移来避免散点重叠,但geom_label_repel默认没有应用相同的偏移规则,所有标签的分类轴坐标都落在分类的中心线位置,因此所有标签都会指向中心线而非对应散点。

修复代码

你只需要给geom_label_repel添加和geom_quasirandom一致的位置调整参数即可,修正后的完整代码如下:

library(ggbeeswarm)
library(tidyverse)
library(ggrepel) # 需额外加载标签绘制所需的依赖库

DataTest <- tibble(Category = c(LETTERS),
                   Year = runif(26, 2016, 2016),
                   Size = runif(26, min = 5, max = 10),
                   SalesGrowth = runif(26, -1, 1))

ggplot() + 
  coord_flip() + 
  geom_quasirandom(DataTest,
                   mapping = aes(factor(Year), 
                                 SalesGrowth,
                                 size = Size)) +
  geom_label_repel(DataTest %>% filter(Category %in% c('A', 'B', 'C')),
                   mapping = aes(factor(Year), 
                                 SalesGrowth,
                                 label = Category),
                   position = position_quasirandom(), # 新增位置调整,和散点偏移规则一致
                   box.padding = 2) +
  scale_size_binned() +
  theme(legend.position = "none")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 15:36:03