Search code examples
rdplyrggvis

How to handle NA value in a ggvis chart?


The following code gives a chart with a single column for the count of a. How do I tell ggvis to consider NA as a group as well? I guess a little hack could be turning NA into a character but I was wondering if there is any more formal way to do that.

data_frame(group=c("a","a",NA)) %>% 
group_by(group) %>% dplyr::summarise(count=n()) %>% 
ggvis(x=~group,y=~count) %>% layer_bars()

Solution

  • You can use the handy function addNA to add an explicit NA-level to factors. This should work as a workaround. Also, ggvis seems to even have problem with the Text label "NA", so you must force it to show that label using scale_nominal("x", domain = c("a", NA)), or rename the label (f.ex. to "<NA>", but that renders as "&lt;NA&gt;" on my RStudio, so it's not a good solution)

    data_frame(group=c("a","a",NA)) %>% 
      mutate(group = addNA(group)) %>%
      group_by(group) %>% dplyr::summarise(count=n()) %>% 
      ggvis(x=~group,y=~count) %>% 
      layer_bars() %>%
      scale_nominal("x", domain = c("a", NA))