A: Creating map by municipality

Asked

Viewed 192 times

0

Hello,

I need to create a map that shows the amount of CPF in Coop. per municipality (ex: blank cities = 0 CPF, dark green cities = 500 CPF).

I did by State and it worked, but when I apply to municipalities, cities with 0 CPF appear colored (example: cities in AL and SE, states that do not have CPF in Coop.).

Another question: how can I improve the resolution of the map? So that, if you zoom into any state, the cities are more visible ?

Below is the code used:

library(readxl)
library(tidyr)
library(tidyverse)
library(dplyr)
library(maptools)
library(rgdal)
library(descr)
library(RColorBrewer)
library(plotrix)
library(reshape2)
library(classInt)

# Tratamento
CPF_MUN_UF_IF <- read_excel("D:/Lupa Econômica/Ricardo/Dados - Credito/Qtd CPF por MUN e UF e TIPO IF.xlsx", sheet = 3, skip=0, range = NULL, col_names = TRUE)
names(CPF_MUN_UF_IF)[1] <- "UF"
names(CPF_MUN_UF_IF)[4] <- "CPF"

# Padronizando nomes de cidades para o Merge
CPF_MUN_UF_IF$MUNICIPIO <- str_to_upper(CPF_MUN_UF_IF$MUNICIPIO) 
CPF_MUN_UF_IF$MUNICIPIO <- chartr("ÃÁÂÉÊÍÓÔÕÚÜÇ","AAAEEIOOOUUC", CPF_MUN_UF_IF$MUNICIPIO)
CPF_MUN_UF_IF$MUNICIPIO <- gsub("D'O", "DO O", CPF_MUN_UF_IF$MUNICIPIO)
CPF_MUN_UF_IF$MUNICIPIO <- gsub("D'A", "DA A", CPF_MUN_UF_IF$MUNICIPIO)
CPF_MUN_UF_IF$MUNICIPIO <- gsub("-", " ", CPF_MUN_UF_IF$MUNICIPIO)

# Agrupando -> quantidade de CPF nas categorias por Estado
MUN_CAT_QTD <- CPF_MUN_UF_IF %>% group_by(MUNICIPIO,UF, Categoria) %>%
  summarise(Qtd = sum(CPF))


# Transformando CPF_MUN_UF_IF em horizontal
teste_mun <- dcast(MUN_CAT_QTD, MUNICIPIO+UF ~ Categoria)
teste_mun [is.na(teste_mun)] <- 0

# Shapefiles
municBR   <- readOGR("D:/Lupa Econômica/Ricardo/Qtd de Coop/dados/MAPA/BRMUE250GC_SIR.shp")
statesBR <- readOGR("D:/Lupa Econômica/Ricardo/Qtd de Coop/dados/MAPA/estados_2010.shp")
regionsBR <-  readOGR("D:/Lupa Econômica/Ricardo/Qtd de Coop/dados/MAPA/regioes_2010.shp")

# Padronizando nomes de cidades para o Merge
municBR@data$NM_MUNICIP <- str_to_upper(municBR@data$NM_MUNICIP) # Deixando tudo maiúsculo
municBR@data$NM_MUNICIP <- chartr("ÃÁÂÉÊÍÓÔÕÚÜÇ","AAAEEIOOOUUC", municBR@data$NM_MUNICIP) # Removendo acentos
#municBR@data$NM_MUNICIP <- gsub("D'O", "DO O",municBR@data$NM_MUNICIP)
#municBR@data$NM_MUNICIP <- gsub("D'A", "DA A",municBR@data$NM_MUNICIP)
#municBR@data$NM_MUNICIP <- gsub("-", " ",municBR@data$NM_MUNICIP)

#Alterando a codificação da base do arquivo .shp (shape):
municBR@data[,1]=str_conv(municBR@data[,1],encoding = "UTF8")


#Removendo os tracos "-" e "'" :
municBR@data[,1]=str_replace_all(municBR@data[,1], "[']", " ") 
municBR@data[,1]=str_replace_all(municBR@data[,1], "[-]", " ") 
#Removendo espaços em branco desnecssarios:
municBR@data[,1]=str_trim(municBR@data[,1])


# Adicionando Cod IBGE - Primeiro Merge
cod_mun <- read.csv("D:/Lupa Econômica/Ricardo/Dados - Credito/MAPA - CPF CRED/cod_mun.csv", sep=";")
cod_mun$X <- NULL # Remove coluna desnecessária
teste_mun <- merge(teste_mun,cod_mun, by.x=c("MUNICIPIO","UF"), by.y=c("municipio","uf"), all.x=T)


# Unindo pelo Cod IBGE
municBR@data$order <- 1:nrow(municBR@data)
municBR@data <- merge(municBR@data, teste_mun, by.x='CD_GEOCMU',by.y='cod_municipio', all.x=T)


# Tirando NA e Transformando em número
municBR@data$ccr <- as.numeric(as.numeric(gsub("[.]", "", as.character(municBR@data$ccr))))
municBR@data[is.na(municBR@data )] <- 0


#levels(as.factor(municBR@data$ccr)) # Contar quantidade de níveis e colocar no createColors()

#Numero de categorias
n.cat = 245

#Cores utilizadas para cada categoria
#brewer.pal.info
myPaletteYlGn <- brewer.pal(9,'YlGn')
createColors  <- colorRampPalette(myPaletteYlGn)
cores <- createColors(245)



#Criando os intervalos de classes para atribuir as cores escolhidas
intervalos=quantile(municBR@data$ccr, probs = seq())

#Criando as classes:
classes <- classIntervals(municBR@data$ccr, n.cat, style= "fixed",
                          fixedBreaks = round(intervalos,2))

#Associando uma cor a uma categoria
corcat <- findColours(classes, cores)

#Plot do mapa com as proporcoes
plot(municBR, col=corcat, lty=0)
plot(statesBR, add=T, lwd=1)
plot(regionsBR, add=T, lwd=1) 


#Acrescentando um titulo
title("CPF em Coop Créd.")

#Acresentando uma legenda
color.legend(xl=-80, xr=-60,yb=-25,yt=-26, 
             legend=c('0','265','530'), 
             rect.col=cores, gradient='x',
             cex=.7, pos=c(1,1,1))
text(x=-69,y=-24,label='Qtd CPF em Cooperativas por Cidade', cex=1)

Ps: how can I get the files to be playable?

EDIT:

I was able to make the map appear right, however, the color caption shows 0 to 245 (number of values) instead of 0 to 529 (number of values). How could I fix?

And I would still like to know how I can improve the resolution of the map.

Thank you.

  • I got the map right. However, the caption is displaying the Labels of the numbers (0 to 245) instead of a gradient from 0 to 529 (maximum number). How to correct?

1 answer

0


The map worked with the following code:

# packages
require(maptools)
require(descr)
require(RColorBrewer)
require(plotrix)
library(tidyverse)
library(dplyr)
library(rgdal)

# Tratamento
CPF_MUN_UF_IF <- read_excel("D:/Lupa Econômica/Ricardo/Dados - Credito/Qtd CPF por MUN e UF e TIPO IF.xlsx", sheet = 3, skip=0, range = NULL, col_names = TRUE)
names(CPF_MUN_UF_IF)[1] <- "UF"
names(CPF_MUN_UF_IF)[4] <- "CPF"

# Padronizando nomes de cidades para o Merge
CPF_MUN_UF_IF$MUNICIPIO <- str_to_upper(CPF_MUN_UF_IF$MUNICIPIO) # Deixando tudo maiúsculo
CPF_MUN_UF_IF$MUNICIPIO <- chartr("ÃÁÂÉÊÍÓÔÕÚÜÇ","AAAEEIOOOUUC", CPF_MUN_UF_IF$MUNICIPIO)# Removendo acentos
CPF_MUN_UF_IF$MUNICIPIO <- gsub("D'O", "DO O", CPF_MUN_UF_IF$MUNICIPIO)
CPF_MUN_UF_IF$MUNICIPIO <- gsub("D'A", "DA A", CPF_MUN_UF_IF$MUNICIPIO)
CPF_MUN_UF_IF$MUNICIPIO <- gsub("-", " ", CPF_MUN_UF_IF$MUNICIPIO)

# Agrupando -> quantidade de CPF nas categorias por Estado
MUN_CAT_QTD <- CPF_MUN_UF_IF %>% group_by(MUNICIPIO,UF, Categoria) %>%
  summarise(Qtd = sum(CPF))


# Transformando CPF_MUN_UF_IF em horizontal
teste_mun <- dcast(MUN_CAT_QTD, MUNICIPIO+UF ~ Categoria)
teste_mun [is.na(teste_mun)] <- 0

# Municipal level data                     ----

# shapefiles
municBR   <- readOGR("D:/Lupa Econômica/Ricardo/mapa ibge/BRMUE250GC_SIR.shp")
statesBR <- readOGR("D:/Lupa Econômica/Ricardo/mapa ibge/BRUFE250GC_SIR.shp")
regionsBR <-  readOGR("D:/Lupa Econômica/Ricardo/Qtd de Coop/dados/MAPA/regioes_2010.shp")

# Adicionando Cod IBGE - Primeiro Merge
cod_mun <- read.csv("D:/Lupa Econômica/Ricardo/Dados - Credito/MAPA - CPF CRED/cod_mun.csv", sep=";")
cod_mun$X <- NULL # Remove coluna desnecessária
teste_mun <- merge(teste_mun,cod_mun, by.x=c("MUNICIPIO","UF"), by.y=c("municipio","uf"), all.x=T)


# merging shapefile and data

# this order var will make it possible to go back to the original order
municBR@data$order <- 1:nrow(municBR@data)

print(municBR@data)

municBR@data <- merge(municBR@data, teste_mun,by.x='CD_GEOCMU',by.y='cod_municipio', all.x=T)
municBR@data$ccr[is.na(municBR@data$ccr)] <- 0

municBR@data$ccr <- as.numeric(as.character(municBR@data$ccr))


levels(as.factor(municBR@data$ccr)) # Contar quantidade de níveis e colocar no createColors()


# plot

#brewer.pal.info
#display.brewer.all()
myPaletteYlGn <- brewer.pal(9,'Paired')
createColors  <- colorRampPalette(myPaletteYlGn)
myColorsYlGn  <- createColors(245)
#check the colors
#pie(rep(1,nrow(statesBR@data)), col=myColorsYlGn, lty=0, labels=NA)


# ordering the vector by ...
municBR@data <- municBR@data[order(municBR@data$ccr),]

# merging GDPcat and their colors
colorOfCats <- data.frame(GDPcat=levels(as.factor(municBR@data$ccr)),colors=unique(myColorsYlGn))
municBR@data <- merge(municBR@data,colorOfCats, by.x='ccr',by.y='GDPcat', all.x=T)

# going back to the original order of the data in the shapefile
municBR@data <- municBR@data[order(municBR@data$order),]
#max.print(municBR@data)

teste_1 <- municBR@data %>% group_by(CD_GEOCMU,cod_uf,UF) %>%
  summarise(Qtd = sum(ccr))

plot(municBR, col=as.character(municBR@data$colors), lty=0, main='Quantidade de CPF em Coop. Créd. por Município') # if you want to emphasize the states boundaries
plot(statesBR, add=T, lwd=1.8)
plot(regionsBR, add=T, lwd=2) # to emphasize the macroregions boundaries

# legend
color.legend(xl=-80, xr=-60,yb=-25,yt=-26, 
             legend=c('0 (Min)','','530 (Máx)'), 
             rect.col=myColorsYlGn, gradient='x',
             cex=.7, pos=c(1,1,1))
text(x=-69,y=-24,label='Qtd CPF em Coop. Créd. por Cidade', cex=0.75)

But I still need help with the caption and the resolution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.