How to plot map with place names – ggplot – R


I downloaded the data and plotted a map with the demographic density of cities in the Metropolitan Region of São Paulo. But it is difficult to identify the cities.

rmsp <- readOGR("rmsp", "MunRM07", stringsAsFactors = F, encoding = "latin1")

rmsp_data <- rmsp@data
rmsp_poligonos <- rmsp@polygons
rmsp_projecao <- rmsp@proj4string

url_munic_15 <- ""
munic_15 <- read.table(url_munic_15, header = T, sep = ";") %>%
   rename(COD_IBGE = A1, ano_pd = A18) %>%
   select(COD_IBGE, ano_pd) %>%
   mutate(ano_pd = as.numeric(as.character(ano_pd)))

rmsp@data <- rmsp@data %>% 
   mutate(ID = as.numeric(ID), COD_IBGE = as.numeric(COD_IBGE),
          DENS_DEMO = as.numeric(DENS_DEMO)) %>%
   left_join(munic_15, by = "COD_IBGE")

 rmsp_df <- fortify(rmsp)

rmsp_df$id <- as.numeric(rmsp_df$id)
   rmsp@data$id <- 0:(nrow(rmsp@data)-1)
   rmsp_df <- left_join(rmsp_df, rmsp@data, by = "id")

ggplot(data = rmsp_df, 
       aes(x = long, y = lat, group = group, fill = DENS_DEMO)) + 
  geom_polygon() +

How to identify the places to get an idea of ​​the positions on the map?


If we put the label function inside aes() before processing the data, for each line in df it will plot a name. We will be left with thousands of repetitions overlapping.

The solution I found was to create an object grouping the names and an average position of the latitudes and longitudes to find where the name will be plotted. I also found it necessary to filter cities by size, as smaller and lesser-known cities overlapped with larger and better-known cities, making localization difficult.

nome_cidade <- rmsp_df %>% # Cria o objeto 
   filter(as.numeric(AREA_KM2) > 100) %>% # Filtra cidades com areas maiores de 100km2
   group_by(NOME) %>% # Agrupa para nomes únicos evitando repetição e sobreposição 
   summarise(long = mean(long), lat = mean(lat)) # Tira a média das coordenadas

Now we will plot the map by inserting the geom_text line with the parameters based on the object created above. She is the one who will put the names.

ggplot(data = rmsp_df, 
       aes(x = long, y = lat)) + 
   geom_polygon(aes(group = group, fill = DENS_DEMO)) +
   geom_text(aes(label = NOME), check_overlap = T, data = nome_cidade, color = "white", size = 3, hjust = 0.5) +

Important to note check_overlap = T if you don't want names overlapping on the map.

Scroll to Top