首页 > 解决方案 > Plotly:用动画图表处理缺失值

问题描述

我发现在使用动画绘图图表时,您需要对每个因素进行相同数量的观察。含义 -> 一个缺失的观察结果会导致整个轨迹在动画图表的整个持续时间内被丢弃。当您使用时间序列数据并且您的一些跟踪开始较晚或结束较早时,这尤其是一个问题。除了为缺失值输入空值之外,还有其他解决方法吗?谢谢!

来自rstudio 社区的交叉发布

例子:

library(gapminder)
library(plotly)
library(dplyr)

#working example with no missings
gapminder %>% 
  group_by(year, continent) %>% 
  summarise(pop = mean(pop), gdpPercap = mean(gdpPercap), lifeExp = mean(lifeExp)) %>%
  plot_ly( x = ~gdpPercap, 
           y = ~lifeExp, 
           size = ~pop, 
           color = ~continent, 
           frame = ~year, 
           text = ~continent, 
           hoverinfo = "text",
           type = 'scatter',
           mode = 'markers')

#filtering one row results in missing Africa trace for entirety of the plot

gapminder %>% 
  group_by(year, continent) %>% 
  summarise(pop = mean(pop), gdpPercap = mean(gdpPercap), lifeExp = mean(lifeExp)) %>%
  filter(gdpPercap > 1253) %>% 
  plot_ly( x = ~gdpPercap, 
           y = ~lifeExp, 
           size = ~pop, 
           color = ~continent, 
           frame = ~year, 
           text = ~continent, 
           hoverinfo = "text",
           type = 'scatter',
           mode = 'markers')

标签: rplotlyr-plotly

解决方案


似乎没有直接的方法可以解决这个问题。间接地,数据框中的 NA 问题可以通过使用 ggplot + ggplotly 而不是 plotly 来解决(请参阅此答案)。此外,当根据我的示例存在不完整的数据集时,可以通过使用 tidyverse 包中的完整函数来解决某些行中的 NA 而不是 NA。

查看解决方案:

p <- gapminder %>%
group_by(year,continent) %>%
summarise(pop = mean(pop), gdpPercap = mean(gdpPercap), lifeExp = mean(lifeExp)) %>%
filter(gdpPercap > 1253) %> %
完成(大陆,年份) %>%
ggplot(aes(gdpPercap,lifeExp,颜色 = 大陆)) +
geom_point(aes(帧 = 年)) + theme_bw()

ggplotly(p)

话虽如此,我不喜欢在生产中使用变通方法,所以请随时告诉我有关 plotly animate 功能的发展。


推荐阅读