如何在gganimate中使用geom_smooth()

时间:2019-04-10 15:03:41

标签: r gganimate

我正在努力了解如何与geom_smooth()一起使用gganimate

reprex在下面可用。在运行除transition_time函数之外的plot语句时,我可以按预期显示静态图。

当我尝试使用transition_time()shadow_mark()来使点保持不变时,使该图成为动态图时,就会出现问题。出现以下错误:

  

$<-.data.frame*tmp*,“组”,值=“”)中的错误:替换   有1行,数据有0

library(readr)
library(tidyr)
library(ggplot2)
library(gifski)
library(gganimate)
library(dplyr)

tst <- readr::read_csv("https://elpais.com/especiales/2019/elecciones-generales/encuestas-electorales/ficheros/tabla.csv?1554807308", 
                       col_types = cols(
                         date = col_date(format = "%d/%m/%y"),
                         house = col_character(),
                         sample = col_double(),
                         turnout = col_double(),
                         PP = col_double(),
                         PSOE = col_double(),
                         UP = col_double(),
                         Cs = col_double(),
                         ERC = col_double(),
                         PDC = col_double(),
                         PNV = col_double(),
                         PAC = col_double(),
                         BIL = col_double(),
                         CC = col_double(),
                         VOX = col_double(),
                         COM = col_double()
                       ))

tst %>% 
  select(date, house, PP, PSOE, UP, Cs, VOX) %>% 
  gather(key = partido, voto, PP, PSOE, UP, Cs, VOX) %>% 
  ggplot(aes(x = date, y = voto, color = partido)) +
  geom_point() + 
  geom_smooth(method = 'loess', formula = 'y ~ x', se = FALSE) +
  transition_time(time = date) + shadow_mark()
Error in `$<-.data.frame`(`*tmp*`, "group", value = ""): replacement
has 1 row, data has 0
In addition: There were 16 warnings (use warnings() to see them)

reprex package(v0.2.1)于2019-04-10创建

我期望的是与此类似的内容(source):

from github link

1 个答案:

答案 0 :(得分:0)

尝试一下:

tmp <- tst %>% 
  select(date, house, PP, PSOE, UP, Cs, VOX) %>% 
  gather(key = partido, voto, PP, PSOE, UP, Cs, VOX) %>%
  filter(!is.na(voto))

ggplot(tmp, aes(x = date, y = voto, color = partido)) + 
  geom_smooth(method = "loess", formula = 'y ~ x', se = FALSE) + 
  geom_point(aes(group = rev(seq_along(date)))) +
  transition_reveal(rev(seq_along(date))) + shadow_mark()