r - 绘图动画 map 不显示具有 NA 值的国家

标签 r maps plotly

我在 plotly community forum 中发布了这个但绝对没有事件!希望你能在这里提供帮助:

我有 map 时间序列数据,有些国家没有数据,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 的 dtaframe 中。

最佳答案

处理此问题的明显方法是为工具提示创建一个单独的标签列,为 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()

给出:

enter image description here

关于r - 绘图动画 map 不显示具有 NA 值的国家,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63660019/

相关文章:

Python:如何绕 z 轴旋转曲面并绘制 3d 图?

r - R plotly中绘图区域上方的位置标题

r - C++ 函数不可用

r - 如果输入已更改,则启用操作按钮

javascript - Carto 多个 map 单个 HTML

java - 如何创建一个接受随机键和值java的映射?

javascript - 从地址变量到谷歌地图

python - 如何在 Plotly 的 plotly 内定位图例

r - 如何使用 dplyr 进行不区分大小写的分组?

r - ggplot2中的渐变填充