geom_segment - 平行闪避

问题描述

我遇到了一个“经典”的 ggplot 问题,与问题 discussed here 非常相似。我试图按照那里的建议解决它,但不知何故它不起作用。

数据集是:

conda update conda

我想做类似的事情:

overall <- structure(list(organization = c("orga_arts","orga_arts","orga_environment","orga_humanrights","orga_labour","orga_neighbor","orga_none","orga_others","orga_party","orga_patriotic","orga_religIoUs","orga_sports","orga_welfare","orga_welfare"),among_participants = c(8.5,8.5,8.7,2.6,11.4,5.4,49.9,4.9,5.6,1,11.8,19.1,4.4,4.4),value = c(10.7,10.6,11.9,11,12.9,10.9,12.8,8.8,4,5.5,3.2,12.3,10.5,12,14.3,6.9,7.8,7.6,6.5,46.9,45.3,45.1,47.7,4.3,5.1,9,4.5,5.8,0.9,1.2,1.7,13.2,12.5,20.8,17.3,19.2,21.5,5.7,5.4),type = c("issue_climate","issue_racism","issue_corona_eco","issue_corona","issue_climate","issue_corona")),row.names = c(NA,-48L),class = "data.frame")

但显然使用平行箭头...我知道我可以做 ggplot(overall) + geom_segment(aes(x = among_participants,xend = value,y=organization,yend=organization,color=type),arrow = arrow(length = unit(0.5,"cm")),position=position_dodge(width=space_between_bars)) ,但后来我错过了箭头,这些箭头对于显示我想到的图形设计的变化方向很重要。

我尝试做类似的事情:

geom_linerange

然后按照上面链接的问题中的建议答案使用 overall$organization_dodged <- ave(as.numeric(overall$organization),overall$organization,FUN = function(x) x + rnorm(length(x),sd = .1)) 执行 geom_segment,但我无法使其正常工作。

我还在 this thread 中看到应该在 10 年前对此进行更新。也许这已经发生了,我在这里错过了一个我现在看不到的简单修复?

我将不胜感激!

解决方法

我敢打赌这可以做得更优雅,但这似乎有效:

space_between_bars <- 0.2
overall$type_y_adj = scale(as.numeric(as.factor(overall$type))) * -space_between_bars
overall$y = as.numeric(as.factor(overall$organization)) + overall$type_y_adj

ggplot(overall) + 
  geom_segment(aes(x = among_participants,xend = value,y=y,yend=y,color=type),arrow = arrow(length = unit(0.1,"cm"))) +
  scale_y_continuous(breaks = 1:length(unique(overall$organization)),labels = unique(overall$organization),minor_breaks = NULL)

enter image description here