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.
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)
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.
Although the accepted answer allows you to add custom colours, it causes the legend to be lost, and I couldn't see how to then add it back.
I think the following method is a bit simpler. It doesn't require a new variable to be created, and retains the legend.
You simple need to use scale_nominal()
to match colours to each level of the grouping variable:
mapDF %>% ggvis(x=~long, y=~lat) %>%
group_by(group) %>%
layer_paths(fill= ~area) %>%
scale_nominal("fill",
domain = c('Mid Atlantic','New York','New England'),
range = c('blue', 'orange', 'red'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.