Reputation: 322
I'm trying to highlight zones on a map based on an associated factor, like so:
My initial problem was that, because the boundaries are overlapping, the zones would display improperly, like this:
I fixed that by hackily subsetting the data, which resulted in the first picture.
#First Map With No Legend
p <- ggplot() +
geom_polygon(data = OpportunityAreas.df[OpportunityAreas.df$Opp_Area == 'Yes',],
aes(long,lat,group=group), fill = "#d2eef7", color = 'black') +
geom_polygon(data = OpportunityAreas.df[OpportunityAreas.df$Opp_Area == 'No',],
aes(long,lat,group=group), fill = "#d2eef7", color = 'orange') +
coord_map()
But now I have no legend and also it just seems like a poor solution. Is there a proper way to color polygon boundaries by an associated factor?
#Second Map With Improper Boundaries
p.improperly.drawn <- ggplot() +
geom_polygon(data = OpportunityAreas.df,
aes(long,lat,group=group, color = Opp_Area), fill = "#d2eef7") +
coord_map()
Upvotes: 1
Views: 590
Reputation: 7790
Your first solution needs only a small tweak to get what you are looking for: move the color
arguments within the geom_polygon
calls to a mapping = aes()
call instead. For the first call, mapping = aes(color = 'black')
and for the second geom_polygon
call use mapping = aes(color = 'orange')
.
I do not have access to the OpportunityAreas.df
in your example so I will use some generic mapping data for my example below.
library(ggplot2)
library(mapdata)
counties <- map_data("county")
ca_county <- subset(counties, region == "california")
ca_county$color <- cut(ca_county$group, 2, labels = c("A", "B"))
ggplot() +
aes(x = long, y = lat, group = group) +
geom_polygon(data = subset(ca_county, color == "A"),
mapping = aes(color = "A"),
fill = NA) +
geom_polygon(data = subset(ca_county, color == "B"),
mapping = aes(color = "B"),
fill = NA)
Upvotes: 2