Search code examples
rfillggvis

Scale_Fill_Manual() for ggvis Map?


I imported some map data and defined three "areas" of interest to me.

library(ggvis)
library(ggplot2)
countyDF <- map_data('county')
statesList = c("new york", "pennsylvania", "massachusetts", "new jersey",
           "connecticut", "maine", "new hampshire", "rhode island", "vermont")

mapDF <- subset(countyDF, region %in% statesList)
mapDF$area <- "New England"
mapDF$area[which(mapDF$region=="new york")] <- "New York"
mapDF$area[which(mapDF$region %in% c("pennsylvania", "new jersey"))] <- "Mid Atlantic" 

Then I plotted the map colored by area:

mapDF %>% ggvis(x=~long, y=~lat) %>%
  group_by(group) %>%
  layer_paths(fill= ~area)

This gives me a nice map, but I would like to adjust the default color palette. Ideally with something like the ggplot2 +scale_fill_manual() option that lets you set specific colors for specific values of a variable. Is there an option to do this in ggvis as well?

As a workaround I created a new "areaColor" variable and then set (:=) the fill to areaColor, but I got the error "length(x) not equal to 1." So I guess I can only set a single value and not a vector of values that I've defined conditionally.


Solution

  • You can use this to change the colours:

    mapDF$colour <- ifelse(mapDF$are == 'New England', 'blue', 
                           ifelse(mapDF$area == 'Mid Atlantic', 'orange', 
                                  ifelse(mapDF$area == 'New York', 'red', '')))
    
    
    mapDF %>% ggvis(x=~long, y=~lat) %>%
      group_by(group) %>%
      layer_paths(fill:= ~colour)
    

    enter image description here

    So essentially you need to create a new column in your data set to reflect the area column and use the := operator to make it work. I don't think there is a ggvis equivalent to scale_fill_manual yet.