ggplot2中geom_segment带箭头平行错位排列的问题求解
解决方法
你需要的功能在ggplot2 v3.3.0及以上版本已经原生支持,无需额外扩展包,只需在映射中显式指定分组即可让position_dodge生效:
library(ggplot2) # 可自行调整错位幅度 space_between_bars <- 0.2 ggplot(overall) + geom_segment( aes( x = among_participants, xend = value, y = organization, yend = organization, color = type, group = type # 核心配置:指定按type分组进行错位 ), arrow = arrow(length = unit(0.5, "cm")), position = position_dodge(width = space_between_bars) )
如果你需要更可控的固定错位效果,不希望受ggplot位置调整逻辑影响,可以用固定偏移手动计算y轴位置,不要用随机数rnorm(会导致每次运行位置不固定、不同组织的同类型条目错位方向不一致):
library(dplyr) # 生成固定错位值 overall <- overall %>% group_by(organization) %>% mutate( # 按type排序计算偏移量,保证同type的条目不错位 offset = as.numeric(factor(type)) - (n_distinct(type)+1)/2, y_dodge = as.numeric(factor(organization)) + offset * 0.1 # 0.1为错位幅度,可自定义 ) ggplot(overall) + geom_segment( aes( x = among_participants, xend = value, y = y_dodge, yend = y_dodge, color = type ), arrow = arrow(length = unit(0.5, "cm")) ) + # 还原y轴分类标签 scale_y_continuous( breaks = seq_along(levels(factor(overall$organization))), labels = levels(factor(overall$organization)), name = "organization" )
内容的提问来源于stack exchange,提问作者Erdne Htábrob
相关产品推荐
相关产品推荐

