Luis Chaves Rodriguez
Luis Chaves Rodriguez

Reputation: 553

Plotly animated map not showing countries with NA values

I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:

I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:

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

Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.

Upvotes: 3

Views: 643

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174596

The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.

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()

Which gives:

enter image description here

Upvotes: 2

Related Questions