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

时间:2017-03-16 23:12:15

标签: r ggplot2 position scatter-plot fill

我正在尝试创建一个带有连接点的散点图。由于我有几个重叠的数据点,我使用position=position_dodge直观地分隔它们。 同时,我用预设的颜色矢量着色点和线。我也试图使用基于因子的条件用黑色填充一些点。 我的问题是,当我尝试添加填充条件时,点的躲闪会搞砸,如下所示:

see these example graphs

以下是如何制作这些图:

# 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"))

1 个答案:

答案 0 :(得分:1)

我认为你只需要将group美学转移到对ggplot的主要调用中,这样它就会适用于点和线的geoms。仅将分组应用于行geom导致闪避的应用不一致。我还将代码的其他几部分移到了对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()

enter image description here

另一件事是,如果您不想,则无需创建单独的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()