3

I need to color in just Costa Rica in a cropped world map of just Central America.

The code I've already written is included below... I would like to be able to do it with the ggplot2 and sf libraries.

library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("maps")
world <- ne_countries(scale='medium',returnclass = 'sf')
class(world)


(CentralAmerica <- ggplot(data = world) +
  geom_sf()  +
  coord_sf(xlim = c(-60, -120), ylim = c(5, 35), expand = FALSE) +
  scale_fill_viridis_d(option = "plasma") +
  theme(panel.background = element_rect(fill = "azure"),
     panel.border = element_rect(fill = NA)))
lwang131
  • 33
  • 3

2 Answers2

3

A more efficient way is to include an if() or ifelse() statement in the:

geom_sf(fill = ifelse(world$geounit == "Costa Rica", 'red', 'blue'))
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
chardonnay
  • 31
  • 3
0

Here's one way. I created a new data table for Costa Rica so that latitude and longitude were easier to get at, then called geom_polygon:

library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("maps")
library("data.table")
world <- ne_countries(scale='medium',returnclass = 'sf')
class(world)

CR_DT <- world[world$name == "Costa Rica",]
CR_DT2 <- as.data.table(CR_DT)[, unlist(geometry)]
CR_DT3 <- setNames(data.table(matrix(nrow = 133, ncol=2)), c("lng", "lat"))
CR_DT3$lng <- CR_DT2[1:133]
CR_DT3$lat <- CR_DT2[134:266]

(CentralAmerica <- ggplot(data = world) +
geom_sf()  +
coord_sf(xlim = c(-60, -120), ylim = c(5, 35), expand = FALSE) +
scale_fill_viridis_d(option = "plasma") +
theme(panel.background = element_rect(fill = "azure"),
      panel.border = element_rect(fill = NA)) +    
geom_polygon(data=CR_DT3, aes(x=lng, y=lat, fill="blue"), colour="red"))

Map of Costa Rica

cgrafe
  • 443
  • 1
  • 6
  • 14