I want to plot regions on map using ggplot and geom_polygons, but i want particular regions to have only borders and others to be filled (I am analyzing only 3 regions but want to show a map of surroundings countries as well)
I am using map_data function and choose regions that i am intrested in c("Syria","Israel","Greece"), but also want to show regions like Egypt and Libya, but only borders, so they dont stand out on visualization.
This is my code:
mapdata = map_data("world", regions =c("Syria","Israel","Greece"))
plot2 = ggplot() + geom_polygon(data = mapdata, aes(x=long, y = lat, group = group)) +
coord_fixed(1.3) + theme_classic()
Later i plot geo points to it.
I tried something like:
dummymap = map_data("world", regions = c("Egypt","Libya"))
[...] + geom_polygon(data = dummymap, aes(x=long, y = lat, group = group)) + theme_bw()
*im changing theme to bw but it outputs Egypt and Libya in classic as well
So i would like Greece, Israel and Syria to be filled and Egypt and Libya only borders
Here is a tidyverse
+ sf
solution
library( tidyverse )
library( sf )
#load countries
mapdata = map_data("world", regions =c("Syria","Israel","Greece","Egypt","Libya"))
#read in points
sf <- st_as_sf( mapdata, coords = c("long", "lat"), crs = 4326 ) %>%
#group geometries by region + subregion, convert to POLYGON
group_by( region, subregion ) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast("POLYGON") %>%
#repeat, but now group by region (=country), and convert to MULTIPOLYGON
group_by( region ) %>%
summarise(geometry = st_combine(geometry)) %>%
st_cast( "MULTIPOLYGON" )
#now plot the different countries, use `fill` to determine fill-color
#and use `aplha` for country-transparancy.
ggplot( data = sf) +
geom_sf( data = sf[ sf$region %in% c("Egypt","Libya"), ], alpha = 0 ) +
geom_sf( data = sf[ sf$region %in% c("Syria","Israel","Greece"), ], fill = "blue" )
result
I'm not sure that converting your data to an sf
-object is necessary, but it allows for easy (and pretty!) plotting in different ways, including powerful options like leaflet
.