library(knitr)
library(tidyverse)
## ── Attaching packages ───────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
## ✔ ggplot2 2.2.1     ✔ purrr   0.2.4
## ✔ tibble  1.3.4     ✔ dplyr   0.7.4
## ✔ tidyr   0.7.2     ✔ stringr 1.3.0
## ✔ readr   1.1.1     ✔ forcats 0.2.0
## ── Conflicts ──────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## Construção de Gráfico de Barras 
### Pernambuco

pernambuco %>% 
  ggplot(aes(x = reorder(Categoria, n), y = n, fill = Categoria)) +
  geom_bar(stat = "identity") + guides(fill = "none") + coord_flip() +
  labs(x = "Categoria", y = "Total", title = "Numero de instituicoes por categoria", subtitle = "Estado de Pernambuco") + coord_flip() +
  geom_label(aes(label = paste(round(100*freq), "%" , sep = "")))  

## Construção de Gráfico de Barras 
### Pernambuco e Paraíba

PE_PB <- base2 %>% 
  select(NO_IES, DS_CATEGORIA_ADMINISTRATIVA, CO_MUNICIPIO_NASCIMENTO) %>% 
  transmute(Nome = NO_IES, 
            Categoria = DS_CATEGORIA_ADMINISTRATIVA, 
            Codigo = as.character(CO_MUNICIPIO_NASCIMENTO) ) %>% 
  mutate(UF = str_sub(string = Codigo, start = 1, end = 2)) %>% 
  group_by(UF, Categoria) %>% 
  summarise(n = n()) %>% mutate(freq = n/sum(n)) %>% 
  filter(UF == "26"|UF == "25") %>% arrange(desc(n)) 

PE_PB
## # A tibble: 12 x 4
## # Groups:   UF [2]
##       UF                   Categoria     n        freq
##    <chr>                       <chr> <int>       <dbl>
##  1    26             Pública Federal   235 0.357686454
##  2    26 Privada com fins lucrativos   159 0.242009132
##  3    26 Privada sem fins lucrativos   152 0.231354642
##  4    25 Privada com fins lucrativos   127 0.376854599
##  5    25             Pública Federal    87 0.258160237
##  6    25 Privada sem fins lucrativos    76 0.225519288
##  7    26            Pública Estadual    63 0.095890411
##  8    25            Pública Estadual    45 0.133531157
##  9    26           Pública Municipal    42 0.063926941
## 10    26                    Especial     6 0.009132420
## 11    25                    Especial     1 0.002967359
## 12    25           Pública Municipal     1 0.002967359
PE_PB %>% mutate(Estado = if_else(UF == "26", "Pernambuco", "Paraíba")) %>% ggplot(aes(x = reorder(Categoria,n), y = n, fill = Estado)) + 
  geom_bar(stat = "identity") + coord_flip()

PE_PB %>% mutate(Estado = if_else(UF == "26", "Pernambuco", "Paraíba")) %>% ggplot(aes(x = reorder(Categoria,n), y = n, fill = Estado)) + 
  geom_bar(stat = "identity", position = "dodge") + coord_flip()

PE_PB %>% mutate(Estado = if_else(UF == "26", "Pernambuco", "Paraíba")) %>% ggplot(aes(x = reorder(Categoria,n), y = n, fill = Estado)) + 
  geom_bar(stat = "identity", position = "dodge") + coord_flip() +
  facet_wrap(~Estado, scales = "free") + guides(fill = "none")