R 手动颜色和条件填充,而不覆盖几何点中的位置减淡?
我试图创建一个带有连接点的散点图。由于我有几个重叠的数据点,我使用R 手动颜色和条件填充,而不覆盖几何点中的位置减淡?,r,ggplot2,position,scatter-plot,fill,R,Ggplot2,Position,Scatter Plot,Fill,我试图创建一个带有连接点的散点图。由于我有几个重叠的数据点,我使用position=position\u dodge将它们直观地分开。 同时,我用预设的颜色向量给点和线上色。我还尝试用黑色填充一些点,使用基于因子的条件。 我的问题是,当我尝试添加填充条件时,圆点的回避会变得混乱,如下所示: 以下是如何绘制这些图: # Creating an example dataframe id<- as.factor(rep(seq(from=1, to=6), times=4)) state &l
position=position\u 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"))
#创建示例数据帧
id我认为您只需要将组
美学移到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\u id
列。您可以使用interaction
功能动态组合sex
和id
。尽管在这种情况下,您还需要创建一个命名的颜色向量,以确保颜色和性别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()
完美的谢谢你的提示!;-)