手动颜色和条件填充而不覆盖 geom_point 中的 position_dodge?

Manual color and conditional fill without overriding position_dodge in geom_point?

我正在尝试创建一个带有连接点的散点图。由于我有几个重叠的数据点,我使用 position=position_dodge 在视觉上将它们分开。 同时,我用预设的颜色矢量为点和线着色。我还尝试使用基于一个因素的条件用黑色填充一些点。 我的问题是,当我尝试添加填充条件时,点的闪避变得混乱,如下所示:

以下是这些绘图的制作方法:

# Creating an example dataframe
id<- as.factor(rep(seq(from=1, to=6), times=4))
state <- rep(c("a", "b", "c", "d"), each=6)
time<-rep(seq(from=3.5, to=9, 0.5), each=2)
yesorno<-rep(c("y", "n", "n"), times=8) # condition for fill
sex<-rep(c(rep("m", times=3), rep("f", times=3)), times=4)

d<-data.frame(id, state, time, yesorno, sex)
d$sex_id <- paste(d$sex, d$id, sep="_") # allows to use two color scales on single plot (orders males and females in alphabetical order)

m <- scales::seq_gradient_pal("lightcyan2", "midnightblue", "Lab")(seq(0,1,length.out = 3)) # used for three male individuals
f<-scales::seq_gradient_pal("burlywood1", "red4", "Lab")(seq(0,1,length.out = 3)) # used for three female individuals
fm<-c(f, m)

ggplot()+
  geom_point(data=d, aes(x=factor(state), y=time, fill= factor(yesorno), color=factor(sex_id)), shape=21, size=3, position=position_dodge(width=0.3))+ # if "fill=..." is removed, then dodging works
  geom_line(data=d, size=0.7, aes(x=factor(state), y=time, color=factor(sex_id), group=factor(sex_id)), position=position_dodge(width=0.3)) +
  scale_color_manual(values=fm)+
  scale_fill_manual(values=c("white", "black"))

我认为你只需要将 group 美学移动到对 ggplot 的主要调用中,这样它就会同时应用于点几何和线几何。仅将分组应用到线几何是什么导致不一致地应用闪避。我还将代码的其他一些部分移到了对 ggplot 的主要调用中,以避免在每个 geom 中重复它们。

pd = position_dodge(0.3)

ggplot(d, aes(x=factor(state), y=time, color=factor(sex_id), group=factor(sex_id)))+
  geom_point(aes(fill=factor(yesorno)), shape=21, size=3, position=pd) + 
  geom_line(size=0.7, position=pd) +
  scale_color_manual(values=fm)+
  scale_fill_manual(values=c("white", "black")) +
  labs(colour="Sex_ID", fill="") +
  theme_classic()

另一件事是,如果您不想,则无需创建单独的 sex_id 列。您可以改为使用 interaction 函数动态组合 sexid。尽管在这种情况下,您还需要创建一个命名的颜色矢量,以确保颜色和 sex_id 按照您想要的方式匹配:

fm = setNames(c(m, f), unique(interaction(d$sex, d$id, sep="_")))

ggplot(d, aes(x=factor(state), y=time, color=interaction(sex, id, sep="_", lex.order=TRUE), 
              group=interaction(sex, id, sep="_", lex.order=TRUE))) +
  geom_point(aes(fill=factor(yesorno)), shape=21, size=3, position=pd) + 
  geom_line(size=0.7, position=pd) +
  scale_color_manual(values=fm)+
  scale_fill_manual(values=c("white", "black")) +
  labs(colour="Sex_ID", fill="") +
  theme_classic()