如何为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
相关产品推荐
相关产品推荐

