Dados

As principais fontes de dados foram:

População

pe <- read_rds("../data/pe_dados.rds")
pe_limits <- read_rds("../data/pe_limits.rds")

data <- pe %>% 
  filter(NM_MUN != 'Fernando de Noronha') %>% 
  mutate(name=factor(NM_MUN, unique(NM_MUN)),
         pop = população/1e6) %>% 
  arrange(pop)

# Criar cortes para escala de cor
cortes <- c(0, 0.01, .05,  .1, .5,  1, 1.5)

# Build the map
ggplot() +
  geom_sf(data = data, fill="grey", alpha=0.3, color = 'white') +
  geom_point(data = data, aes(x=longitude, y=latitude, size=pop, fill=pop, alpha=pop), shape=21, colour="black", stroke=1) +
  scale_size_continuous(name="População (em Milhões)", trans="log", 
                        range=c(.5,5), breaks=cortes) +
  scale_alpha_continuous(name="População (em Milhões)", trans="log", 
                         range=c(0.1, .95), breaks=cortes) +
  scale_fill_viridis(option="magma", trans="log",
                      breaks=cortes, name="População (em Milhões)" ) +
  theme_void() + 
  coord_sf() + 
  guides( fill = guide_legend()) +
  #ggtitle("População dos municípios de Pernambuco") +
  theme(legend.direction = "horizontal",
        legend.position = "bottom", #c(0.85, 0.8),
        text = element_text(color = "#22211d"),
        plot.background = element_rect(fill = "#f5f5f2", color = NA),
        panel.background = element_rect(fill = "#f5f5f2", color = NA),
        legend.background = element_rect(fill = "#f5f5f2", color = NA),
        #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
  )

data <- pe %>% 
  filter(NM_MUN != 'Fernando de Noronha') %>% 
  mutate(name=factor(NM_MUN, unique(NM_MUN)),
         pop = população/1e6,
         scale = rescale((log(pop)), to = c(1500, 15000))) %>% 
  arrange(pop) %>% 
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Cidade:</strong> ", name, "\n", 
    "</br><strong>População:</strong> ", format(população, decimal.mark = ",", big.mark = "."), sep="")
  ))


pal <- colorBin(viridis_pal(option = "magma")(6), data$scale, bins = rescale((log(cortes)), to = c(1500, 15000)))

caption <- tags$div(
             HTML('<span>(log) População dos Municípios de Pernambuco</span>')
           )

data %>% 
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircles(lng = ~longitude, lat = ~latitude,
             radius = ~scale,
             fillColor = ~pal(scale),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             highlightOptions = highlightOptions(
               weight = 5,
               color = "black",
               dashArray = NULL,
               fillOpacity = 0.7,
               bringToFront = TRUE),
             fillOpacity = ~rescale(scale, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "bottomleft")

Nascimentos nos últimos 5 anos

Nascimentos em municípios que não residem.

data <- read_rds("../data/nascimento_outro_municipio.rds")

pal <- colorNumeric(viridis_pal(option = "magma")(10), data$scale)

caption <- tags$div(
             HTML('<span>(log) Número de nascimentos de não residentes (externos)</span>')
           )

data %>%
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircles(lng = ~longitude, lat = ~latitude,
             radius = ~scale,
             fillColor = ~pal(scale),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             highlightOptions = highlightOptions(
               weight = 5,
               color = "black",
               dashArray = NULL,
               fillOpacity = 0.7,
               bringToFront = TRUE),
             fillOpacity = ~rescale(scale, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "topright")
breaks = c(0, 10000, 20000, 50000, 140000, 150000)
ggplot() +
    geom_sf(data = data %>% filter(NM_MUN != "Fernando de Noronha"), fill="grey", alpha=0.3, color = 'white') +
    geom_point(data = data %>% filter(NM_MUN != "Fernando de Noronha"), aes(x=longitude, y=latitude, size=externos, fill=externos, alpha=externos), shape=21, colour="black", stroke=1) +
    scale_size_continuous(name="Nascimentos externos", #trans="log", 
                          range=c(1,12), labels = comma, breaks = breaks) +
    scale_alpha_continuous(name="Nascimentos externos", #trans="log", 
                           range=c(0.4, .95), labels = comma, breaks = breaks) +
    scale_fill_gradient(low = "green", high = "red", name="Nascimentos externos", labels = comma, breaks = breaks) +
    theme_void() + 
    coord_sf() + 
    guides( fill = guide_legend()) +
    #ggtitle("População dos municípios de Pernambuco") +
    theme(legend.direction = "horizontal",
          legend.position = "bottom", #c(0.85, 0.8),
          text = element_text(color = "#22211d"),
          plot.background = element_rect(fill = "#f5f5f2", color = NA),
          panel.background = element_rect(fill = "#f5f5f2", color = NA),
          legend.background = element_rect(fill = "#f5f5f2", color = NA),
          #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm"))
    )

Matriz de custo

A matriz de custo principal será a matriz de distäncia enrte as cidades de Pernambuco. A dimensão da matriz é \(185\times 185\).

costmatrix_table <- read_rds("../data/costmatrix_table.rds")

costmatrix_table %>% 
      arrange(Origem) %>% 
      select(Origem = município_origem, Destino = município_destino, `Distância (em Metros)` = Distância) %>% 
      DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(#list(className = 'dt-left', targets = c(0,1)),
                                         list(className = 'dt-center', targets = c(0,1,2)),
                                         #list(className = 'dt-right', targets = c(8)),
                                         list(bSortable = TRUE, targets = 0:2) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(3), digits = 0, dec.mark = ",", mark = ".")

Custo nos últimos 5 anos (2018 a 2022)

cost18a22 <- read_rds("../data/cost18a22.rds")

cost18a22 %>% 
  arrange(-n) %>% 
  select(Origem = município_origem, Destino = município_destino, n, Distância) %>% 
  mutate(`Média Anual` = n/5) %>% 
  rename(`Nascimentos` =  n) %>% 
        DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(#list(className = 'dt-left', targets = c(0,1)),
                                         list(className = 'dt-center', targets = c(0,1,2,3,4)),
                                         #list(className = 'dt-right', targets = c(8)),
                                         list(bSortable = TRUE, targets = 0:4) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatRound(columns = c(3,4,5), digits = 0, dec.mark = ",", mark = ".")
value_box(
  title = "Verificar", 
  theme_color = "warning",
  value = "Natimortos entram na base do SINASC?",
  showcase = bs_icon("patch-question"),
  p("André Leite", bs_icon("emoji-smile"))
)
Verificar Natimortos entram na base do SINASC?

André Leite

Nascimento por Estabelecimento

estab_nascimento <- read_rds("../data/estab_nascimento.rds")

data <- estab_nascimento %>% 
    left_join(pe %>% 
                st_drop_geometry() %>% 
                select(ibge = CD_MUN, Município = NM_MUN) %>% 
                mutate(ibge = str_sub(ibge, 1, 6)), 
              by = join_by(ibge)) %>% 
  mutate(Ordem = row_number()) 

data %>%   select(Ordem,
         Nome = nome,
         Nascimentos = n,
         Município,
         `Proporção` = prop,
         Acumulado = acumulado) %>% 
     DT::datatable(
        rownames = FALSE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(list(className = 'dt-left', targets = c(0)),
                                         list(className = 'dt-center', targets = 1:5),
                                         list(bSortable = TRUE, targets = 0:5) #,
                                         #list(visible = FALSE, targets = c(3, 8:9))
                       )#,
        #               rowCallback=JS(
        #                 'function(row,data) {                                                #              if($(row)["0"]["_DT_RowIndex"] % 2 <1)
        #                 $(row).css("background","#f2f9ec") //#e8f5e9
        #                 }')
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
      formatPercentage(columns = c(5,6))
breaks = c(0, 5000, 10000, 20000, 30000, 40000)

ggplot() +
    geom_sf(data = pe_limits, fill="grey", alpha=0.3, color = 'white') +
    geom_point(data = data %>% 
                 filter(`Município` != "Fernando de Noronha") %>% 
                 mutate(longitude = as.numeric(longitude),
                        latitude = as.numeric(latitude)) %>% 
                 filter((!is.na(latitude))|(!is.na(longitude))) %>% 
                 arrange(n), 
               aes(x=longitude, 
                   y=latitude, 
                   size=n, fill=n, alpha=n), 
               shape=21, colour="black", stroke=1) +
    scale_size_continuous(name="Nascimentos", #trans="log", 
                          range=c(1,12), labels = comma, breaks = breaks) +
    scale_alpha_continuous(name="Nascimentos", #trans="log", 
                           range=c(0.25, .95), labels = comma, breaks = breaks) +
    scale_fill_gradient(low = "green", high = "red", name="Nascimentos", labels = comma, breaks = breaks) +
    theme_void() + 
    coord_sf() + 
    guides( fill = guide_legend()) +
    #ggtitle("População dos municípios de Pernambuco") +
    theme(legend.direction = "horizontal",
          legend.position = "bottom", #c(0.85, 0.8),
          text = element_text(color = "#22211d"),
          plot.background = element_rect(fill = "#f5f5f2", color = NA),
          panel.background = element_rect(fill = "#f5f5f2", color = NA),
          legend.background = element_rect(fill = "#f5f5f2", color = NA),
          #plot.title = element_text(size= 14, color = "#4e4d47", hjust=.5, vjust = 4,  margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm"))
    )

pal <- colorNumeric(viridis_pal(option = "magma")(10), data$n)

caption <- tags$div(
             HTML('<span>(log) Número de nascimentos por Estabelecimento</span>')
           )

data %>% 
  mutate(longitude = as.numeric(longitude),
  latitude = as.numeric(latitude)) %>% 
  filter((!is.na(latitude))|(!is.na(longitude))) %>% 
  arrange(n) %>%   
  rowwise() %>% 
  mutate(text = HTML(paste(
    "<strong>Município:</strong> ", Município, "\n", 
    "</br><strong>Estabelecimento:</strong> ", nome,
    "</br><strong>Nascimentos:</strong> ", format(n, decimal.mark = ",", big.mark = "."), 
    "</br><strong>Proporção:</strong> ", format(prop, decimal.mark = ",", big.mark = ".", digits = 2),
    sep=""))) %>% 
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>% 
  addPolygons(data = pe_limits, weight = 2, color = "black", fillOpacity = 0) %>% 
  addCircleMarkers(lng = ~longitude, lat = ~latitude,
             radius = ~rescale(n, to = c(2, 15)),
             fillColor = ~pal(n),
             color = "black",
             stroke = TRUE,
             opacity = .3,
             weight = 2, 
             # highlightOptions = highlightOptions(
             #   weight = 5,
             #   color = "black",
             #   dashArray = NULL,
             #   fillOpacity = 0.7,
             #   bringToFront = TRUE),
             fillOpacity = ~rescale(n, to = c(.1, .9)),
             label = ~text,
             labelOptions = labelOptions(
               style = list("font-weight" = "normal", padding = "3px 8px"),
               textsize = "10pt",
               direction = "auto")) %>% 
  fitBounds(lng1 = -41.358336,
            lat1 = -9.482897,
            lng2 = -34.806691,
            lat2 = -7.272954) %>% 
  addControl(caption, position = "topright")

Dados de Leitos

monnb <- function(d) { 
  lt <- as.POSIXlt(as.Date(d, origin="1900-01-01"))
  lt$year*12 + lt$mon 
} 

nascimentos <- read_rds("../data/nasc5a.rds") 
leitos <- read_parquet("../data/leitos_pe.parquat")
  
data <- nascimentos %>% 
  filter(str_sub(CODMUNNASC , 1, 2) == "26") %>% 
  group_by(CODMUNNASC) %>% 
  summarise(Nascimentos = n(), 
            Fim = max(date, na.rm = TRUE), 
            Inicio  = min(date, na.rm = TRUE)) %>% 
  mutate(Amplitude_dias = Fim - Inicio,
         Amplitude_meses = monnb(Fim) -monnb(Inicio),
         `Média Diária` = ceiling(Nascimentos/as.numeric(Amplitude_dias)),
         `Média Mensal` = ceiling(Nascimentos/as.numeric(Amplitude_meses))) %>% 
  left_join(leitos, by = c("CODMUNNASC" = "ibge")) %>% 
  filter(!is.na(Município)) %>% 
  arrange(-Obstétrico) %>% rename(Pedriátrico = Pediátrico) %>% 
  select(-Inicio, -Fim, -Amplitude_dias, -Amplitude_meses) %>% 
  filter(!is.na(Pedriátrico))


data %>%   
  select(Município,
         Nascimentos,
         `Média Diária`,
         `Média Mensal`,
         `Leitos Obstétricos` = Obstétrico,
         `Total de Leitos` = Total) %>% 
     DT::datatable(
        rownames = TRUE,
        escape = FALSE,
        options = list(autoWidth = TRUE,
                       #fixedColumns = FALSE,
                       dom = 'tp',
                       #scrollX = TRUE,
                       pageLength = 20,
                       columnDefs = list(list(className = 'dt-left', targets = c(1)),
                                         list(className = 'dt-center', targets = c(0, 2:6)),
                                         list(bSortable = TRUE, targets = 0:6) 
                       )
        ),
        class = "stripe compact hover",
        style = 'auto' #, extensions = 'Responsive'
      ) %>% 
  formatRound(columns = c(2:6), mark = ".", dec.mark = ",", digits = 0) 

Modelagem

Outros códigos

layout_column_wrap(
  width = "250px",
  value_box(
    title = "1st value", 
    value = "123",
    showcase = bs_icon("bar-chart"),
    p("The 1st detail")
  ),
  value_box(
    title = "2nd value", 
    value = "456",
    showcase = bs_icon("graph-up"),
    p("The 2nd detail"),
    p("The 3rd detail")
  ),
  value_box(
    title = "3rd value", 
    value = "789",
    showcase = bs_icon("pie-chart"),
    p("The 4th detail"),
    p("The 5th detail"),
    p("The 6th detail")
  )
)
1st value 123

The 1st detail

2nd value 456

The 2nd detail

The 3rd detail

3rd value 789

The 4th detail

The 5th detail

The 6th detail

sparkline <- plot_ly(economics) %>%
  add_lines(
    x = ~date, y = ~psavert,
    color = I("white"), span = I(1),
    fill = 'tozeroy', alpha = 0.2
  ) %>%
  layout(
    xaxis = list(visible = F, showgrid = F, title = ""),
    yaxis = list(visible = F, showgrid = F, title = ""),
    hovermode = "x",
    margin = list(t = 0, r = 0, l = 0, b = 0),
    font = list(color = "white"),
    paper_bgcolor = "transparent",
    plot_bgcolor = "transparent"
  ) %>%
  config(displayModeBar = F) %>%
  htmlwidgets::onRender(
    "function(el) {
      var ro = new ResizeObserver(function() {
         var visible = el.offsetHeight > 200;
         Plotly.relayout(el, {'xaxis.visible': visible});
      });
      ro.observe(el);
    }"
  )

layout_column_wrap(
  width = 1/2,
value_box(
  title = "Personal Savings Rate",
  value = "7.6%",
  p("Started at 12.6%"),
  p("Averaged 8.6% over that period"),
  p("Peaked 17.3% in May 1975"),
  showcase = sparkline,
  full_screen = TRUE,
  theme_color = "success"
)
)
Personal Savings Rate 7.6%

Started at 12.6%

Averaged 8.6% over that period

Peaked 17.3% in May 1975


When running this document with {thematic} installed, the thematic::thematic_rmd(font = "auto") effectively translates theme (CSS) settings to new global theming defaults for {ggplot2}, {lattice}, and {base} R graphics:

ggplot2

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
    geom_point() + geom_smooth()

lattice

lattice::show.settings()

base

plot(pressure, col = thematic::thematic_get_option("accent"))

Stay tuned