Plotly动画地图不显示带有NA值的国家。

3
我在plotly社区论坛中发布了这篇文章,但完全没有活动!希望你能在这里提供帮助:
我有地图时间序列数据,一些国家没有数据,plotly根本不会绘制它们。我可以将它们轮廓化并使其看起来不同,但似乎没有任何地方显示数据缺失(即我想要一个图例条目)。我该如何实现这一点?以下是一个示例:
library(plotly)
library(dplyr)

data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')


l <- list(color = toRGB("grey"), width = 0.5)

g <- list(
  scope = 'world',
  countrycolor = toRGB('grey'),
  showframe = T,
  showcoastlines = TRUE,
  projection = list(type = 'natural earth')
)

map.time = data %>%
  plot_geo() %>% 
  add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
            text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>% 
  colorbar(title = 'Confirmed') %>%
  layout(
    title = 'Number of confirmed cases over time',
    geo = g
  ) %>% 
  animation_opts(redraw = F) %>%
  animation_slider(
    currentvalue = list(
      prefix = paste0("Days from ",
                      format(StartDate, "%B %dnd"),": "))) %>%
  plotly_build()

map.time


请注意,缺少数据的国家(例如俄罗斯)具有与所有其他国家一样多的数据点,问题不在于它们未出现在传递给Plotly的数据框中。
1个回答

2
处理这个问题的明显方法是为提示框创建一个单独的标签列,对于NA值,标签应显示“无数据”(否则显示实际值),然后将真正的NA值设为0。这样可以使所有国家的外观保持统一,但正确地告诉您哪些国家没有数据。
map.time = data %>%
  mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
  plot_geo() %>% 
  add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
            text = ~Country, locations = ~Alpha.3.code, 
            marker = list(line = l)) %>% 
  colorbar(title = 'Confirmed') %>%
  layout(
    title = 'Number of confirmed cases over time',
    geo = g
  ) %>% 
  animation_opts(redraw = F) %>%
  animation_slider(
    currentvalue = list(
      prefix = paste0("Days from ",
                      format(StartDate, "%B %dnd"),": "))) %>%
  plotly_build()

这将会得到:

在此输入图片描述


嗨,艾伦,感谢您的快速回复。理想情况下,我希望有一个单独的图例框,上面写着“NA”,以清楚地区分有缺失值和没有缺失值的国家。在我看来,使用“-1”而不是“NA”并不理想,因为这样这些国家的颜色会与低值国家的颜色混合在一起。 - Luis Chaves Rodriguez

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