gganimate: 处理缺失值

3

我第一次尝试使用 gganimate 包,在处理缺失值 (NA) 时遇到了问题。如果我的问题很基础,我向您道歉,但我找不到任何解决方案。

这是一个可重现的示例:

# Load libraries:
library(ggplot2)
library(gganimate)
library(dplyr)
library(tidyr)  

# Create some data
  ## Monthly sales are in 100:1000
  ## Expected sales are 400/month, increasing by 5% every year
set.seed(123)
df <- data_frame(Year = rep(2015:2018, each=12),
                 Month = rep(1:12, 4),
                 Sales = unlist(lapply(1:4, 
                           function(x){cumsum(sample(100:1000, 12))})),
                 Expected = unlist(lapply(1:4, 
                           function(x){cumsum(rep(400*1.05^(x-1),12))})))

# gganimate works fine here:
df %>% 
    tidyr::gather("Type", "value", Sales:Expected) %>%
    ggplot(aes(Month, value, col=Type)) +
        geom_point() +
        geom_line() +
        gganimate::transition_time(Year)

# Now data for the end of Year 2018 are missing:
df[df$Year==2018 & df$Month %in% 9:12,"Sales"] = NA

# Plotting with ggplot2 works (and gives a warning about missing values):
df %>% 
    tidyr::gather("Type", "value", Sales:Expected) %>%
    dplyr::filter(Year == "2018") %>%
    ggplot(aes(Month, value, col=Type)) +
        geom_point() +
        geom_line()

# But gganimate fails
df %>% 
    tidyr::gather("Type", "value", Sales:Expected) %>%
    ggplot(aes(Month, value, col=Type)) +
        geom_point() +
        geom_line() +
        gganimate::transition_time(Year) 

# I get the following error: 
## Error in rep(seq_len(nrow(polygon)), splits + 1) : incorrect 'times' argument

我尝试使用 gganimateenter_() / exit_() 函数进行操作,但未成功。
感谢您的帮助。

编辑:(使用 MattL 的建议)
这个可以运行:

df %>% 
    # filter(!is.na(Sales)) %>% ##Proposed by Matt L but removes Expected values too
    gather("Type", "value",Sales:Expected) %>%
    filter(!is.na(value)) %>% ## Remove NA values
    ggplot(aes(Month, value, col=Type)) +
        geom_point() +
        geom_line() +
        labs(title = "Year: {frame_time}") + ## Add title
        gganimate::transition_time(Year) +
        gganimate::exit_disappear(early=TRUE) ## Removes 2017 points appearing in Year 2018

我仍然觉得gganimate应该像ggplot一样处理这些NA值。谢谢!


1
如果您在管道符号 gatherggplot 命令之前添加 filter(!is.na(Sales)) %>%,它应该可以正常工作。 - Matt L.
1
谢谢您的回答。是的,那个方法可行。这种解决方案的问题在于它还会删除“Expected”的值。然而,在gather之后应用filter(!is.na(value))也可以正常工作。此外,在动画中,对应于2017年9月至12月(销售和预期)的点仍然停留在2018年。我使用以下方式解决了这个问题:+ gganimate::exit_disappear(early=TRUE)。我已经在我的问题中编辑了这个解决方案。再次感谢。 - Pascal Martin
1个回答

1
在“管道”到ggplot函数之前过滤掉缺失值:
df %>% 
    filter(!is.na(Sales)) %>% 
    tidyr::gather("Type", "value", Sales:Expected) %>%
    ggplot(aes(Month, value, col=Type)) +
        geom_point() +
        geom_line() +
        gganimate::transition_time(Year) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接