【问题标题】:ggplot2 and gganimate: How to make an animated line change colors depending on Y axis valuesggplot2 和 gganimate:如何使动画线根据 Y 轴值改变颜色
【发布时间】:2018-03-30 23:19:37
【问题描述】:

我希望情节中的动画线在超过 50% 时改变颜色,以显示结果的差异。

我的“data.thesis”框架如下所示:

我假设的结果图在这里。代码将为绘图设置动画,以便黑线移动到潜在结果:

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)

【问题讨论】:

    标签: r animation ggplot2 gganimate


    【解决方案1】:

    不要硬编码线条颜色,而是在第二次调用geom_errorbar 时使用颜色美学。具体来说,将第二个 geom_errorbar 语句从这里更改:

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

    到这里:

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

    这不是特定于gganimate,因为这正是您对任何 ggplot 所做的,以使线条颜色取决于超过某个 y 轴切割点。

    在下面的图中,我添加了+ scale_colour_manual(values=c(Win="blue", Lose="red")),但您可以将颜色设置为您想要的任何值。另外,我在 y=55 处留下了红线注释。我不确定你是否希望在最终情节中使用它,但它当然可以很容易地删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-29
      • 2015-01-17
      • 1970-01-01
      • 2021-01-13
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多