ggplot:基于类别的位置闪避

ggplot: position dodge based on category

我想使用 position dodge 来偏移我的 ggplot 图表中的一个变量(在本例中为香蕉),并让其他两个变量(red_apple 和 green_apple)不偏移。使用 position_dodge 将偏移应用于每个变量,但我想选择具体偏移哪些变量。

library(ggplot2)

data <- data.frame(Place = c(rep('Place_A',30),rep('Place_B',30)),
                   variable =     c(rep(c(rep('red_Apple',10),rep('green_Apple',10),rep('bananna',10)),2)),
                   value = rep(c(1:10,1:10-.05,1:10+.2),2))

dodge = position_dodge(.5)

ggplot(data, aes(Place, value)) + 
  geom_point(aes(color=variable),position=dodge)

例如,是否有一种手动缩放位置的方法,就像您可以如何处理其他美学一样? 这显然会引发错误,但正是我所希望的...

ggplot(data, aes(Place, value)) + 
  geom_point(aes(color=variable, position = variable)) + 
  scale_position_manual(breaks = c('green_Apple','red_Apple','bananna'),
                      values = c(position_dodge(0),position_dodge(0),position_dodge(.5)))

这看起来像你想要的吗?

data$grp = ifelse(data$variable == "bananna", 2, 1)
ggplot(data, aes(Place, value, group = grp)) + 
  geom_point(aes(color=variable), position = position_dodge(0.5))