2017-03-16 13 views
1

연결점이있는 scatterplot을 만들려고합니다. 중복되는 데이터 요소가 여러 개 있기 때문에 position=position_dodge을 사용하여 시각적으로 구분했습니다. 동시에, 미리 설정된 색상의 벡터로 도트와 선을 색칠하고 있습니다. 나는 또한 요인에 근거한 조건을 사용하여 검은 점들로 채우기를 시도하고있다.geom_point에서 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

당신은 단지 group 미학을 ggplot에 대한 주된 호출로 옮겨야 할 필요가 있다고 생각합니다. 그래서 포인트와 라인 기하학 모두에 적용될 것입니다. 라인 기하 구조에만 그룹핑을 적용하면 도징이 일관성없이 적용됩니다. 또한 코드의 다른 부분을 ggplot에 대한 기본 호출로 이동하여 각 기하 구조에서 반복하지 않아도되도록했습니다.

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을 즉석에서 결합 할 수 있습니다. 이 경우 색상과 섹스 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() 
+0

Perfect! 팁 고마워! ;-) –