首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >gganimate:缺失值的处理

gganimate:缺失值的处理
EN

Stack Overflow用户
提问于 2018-08-18 20:26:46
回答 1查看 918关注 0票数 3

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

下面是我正在尝试做的一个可重复的例子:

代码语言:javascript
复制
# 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的建议)

这是可行的:

代码语言:javascript
复制
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值。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2018-08-19 00:02:18

过滤掉“管道”之前的缺失值到ggplot函数:

代码语言:javascript
复制
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) 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51908650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档