2017-10-19 9 views
2

내 플롯에서 애니메이션 선이 50 % 이상일 때 색상을 변경하여 결과의 ​​차이를 표시하고 싶습니다.ggplot2 및 gganimate : 애니메이션 선을 Y 축 값에 따라 색상을 변경하는 방법

내 "data.thesis"프레임은 다음과 같습니다

image1

내 가상의 결과 플롯이 여기에있다. 검은 선이 잠재적 인 결과로 이동하도록 코드는 플롯을 애니메이션 것

image2

library(ggplot2) 
library(gganimate) 

z <- qnorm(0.33) 
sd <- (50 - 55)/z 
moe <- 1.96*sd 

data.thesis <- data.frame(name = "Candidate", percent.vote = 55) 
data.thesis <- data.thesis %>% 
    mutate(sd = sd, 
     ymin = percent.vote - 1.96*sd, 
     ymax = percent.vote + 1.96*sd) 


set.seed(2016) 
n.outcomes <- 50 

df <- data.frame(simulation = 1:n.outcomes, 
       team = "Yes", 
       vote.share = round(rnorm(50, mean = 55, sd = sd), 3)) 

p <- df %>% 
    ggplot(aes(x = team, y = vote.share)) + 
    geom_errorbar(aes(
    ymin = vote.share, ymax = vote.share, 
    frame = simulation, cumulative = TRUE), 
    color = "grey80", alpha = 1/8) + 
    geom_errorbar(aes(
    ymin = vote.share, ymax = vote.share, frame = simulation), 
    color = "black") + 
    theme(panel.background = element_rect(fill = "#FFFFFF"), 
     text=element_text(size=15, vjust=1, family="Verdana"), 
     axis.title.x=element_blank(), 
     axis.text.x=element_blank(), 
     axis.ticks.x=element_blank()) + 
    labs(title = "", y = "Vote share", x = "") + 
    scale_y_continuous(limits=c(0, 100), 
        breaks=c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)) + 
    xlab("") + 
    ylab("Percent") + 
    ggtitle("Treatment 2: Hypothetical Outcome Plot") + 
    annotate("segment", x=1.6, xend=1.6, y=51, yend=70, colour="black", size=1, arrow=arrow()) + 
    annotate(geom="text", x=1.6, y=74, label="A Wins", color="black", size=5) + 
    annotate("segment", x=1.6, xend=1.6, y=49, yend=30, colour="black", size=1, arrow=arrow()) + 
    annotate(geom="text", x=1.6, y=26, label="A Loses", color="black", size=5) + 
    annotate("text", x = 1.8, y = 75, label = "") + 
    annotate("segment", x=.55, xend=1.45, y=55, yend=55, colour="red") 

gganimate(p, title_frame = FALSE) 

답변

0

대신 하드 코딩 선 색상을 geom_errorbar에 두 번째 호출에 컬러 미학을 사용합니다. 이 모든 ggplot 선을 만들기 위해 당신이 할 것입니다 정확히 한,이 gganimate 특정하지 않습니다

geom_errorbar(aes(ymin = vote.share, ymax = vote.share, frame = simulation, 
    colour=ifelse(vote.share > 50, "Win","Lose")), show.legend=FALSE) + 

이에

geom_errorbar(aes(ymin = vote.share, ymax = vote.share, frame = simulation), 
    color = "black") + 

: 특히이에서 두 번째 geom_errorbar 문을 변경 일부 y 축 절단 점을 초과하면 색상이 달라집니다.

아래 플롯에서 + scale_colour_manual(values=c(Win="blue", Lose="red"))을 추가했으나 원하는 값으로 색상을 설정할 수 있습니다. 또한 y = 55에 빨간색 선 주석을 남겼습니다. 나는 당신이 최종 음모에 그것을 원한다면 확실하지 않지만, 당연히 쉽게 제거 될 수 있습니다.

enter image description here

+0

이것은 완벽하게 작동했습니다. 정말 고맙습니다! –