---
title: "Día 6 #30díasdegráficos (gráficos de donuts). Población en edad de trabajar por distrito y departamento (% sobre población total). Perú 2015 (ESP)"
author: "Rubén F. Bustillo"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    source_code: embed
    vertical_layout: fill
    theme: lumen
---



```{r setup, include=FALSE}


# PACKAGES / LIBRARIES:

library(flexdashboard)
library(tidyverse)
library(readxl)
library(tidyverse)
library(circlize)
library(viridis)


# Este gráfico está hecho siguiendo las indicaciones de: https://www.r-graph-gallery.com/297-circular-barplot-with-groups.html


circle_plot <- read_excel("C:/Users/Usuario/Desktop/r_que_r/r_que_r/content/datasets/circle_plot.xlsx")


circle_plot$ubigeo <- as.character(circle_plot$ubigeo)

df <- circle_plot %>%
  filter(Nivel == "PROV") %>%
  separate(ubigeo, c("Region", "Province"), 2) %>%
  mutate(Departamento = if_else(Region == "01", "Amazonas", Region)) %>%
  mutate(Departamento = if_else(Region == "02", "Áncash", Departamento )) %>%
  mutate(Departamento = if_else(Region == "03", "Apurímac", Departamento )) %>%
  mutate(Departamento = if_else(Region == "04", "Arequipa", Departamento )) %>%
  mutate(Departamento = if_else(Region == "05", "Ayacucho", Departamento )) %>%
  mutate(Departamento = if_else(Region == "06", "Cajamarca", Departamento ))%>%
  mutate(Departamento = if_else(Region == "07", "Callao", Departamento ))%>%
  mutate(Departamento = if_else(Region == "08", "Cusco", Departamento ))%>%
  mutate(Departamento = if_else(Region == "09", "Huancavelica", Departamento ))%>%
  mutate(Departamento = if_else(Region == "10", "Huánuco", Departamento ))%>%
  mutate(Departamento = if_else(Region == "11", "Ica", Departamento ))%>%
  mutate(Departamento = if_else(Region == "12", "Junín", Departamento ))%>%
  mutate(Departamento = if_else(Region == "13", "La Libertad", Departamento ))%>%
  mutate(Departamento = if_else(Region == "14", "Lambayeque", Departamento ))%>%
  mutate(Departamento = if_else(Region == "15", "Lima", Departamento ))%>%
  mutate(Departamento = if_else(Region == "16", "Loreto", Departamento ))%>%
  mutate(Departamento = if_else(Region == "17", "Madre de Dios", Departamento ))%>%
  mutate(Departamento = if_else(Region == "18", "Moquegua", Departamento ))%>%
  mutate(Departamento = if_else(Region == "19", "Pasco", Departamento ))%>%
  mutate(Departamento = if_else(Region == "20", "Piura", Departamento ))%>%
  mutate(Departamento = if_else(Region == "21", "Puno", Departamento ))%>%
  mutate(Departamento = if_else(Region == "22", "San Martín", Departamento ))%>%
  mutate(Departamento = if_else(Region == "23", "Tacna", Departamento ))%>%
  mutate(Departamento = if_else(Region == "24", "Tumbes", Departamento ))%>%
  mutate(Departamento = if_else(Region == "25", "Ucayali", Departamento )) %>%
  select(Provincia, Departamento, PET)
  
df$Departamento <- as.factor(df$Departamento)
df$Provincia <- as.factor(df$Provincia)


```

```{r, out.width="100%"}

# Líneas vacias entre grupos de provincias 
empty_bar <- 2

# dataframe para unir a nuestro dataframe (df)
para_juntar <-  data.frame(matrix(NA, empty_bar*nlevels(df$Departamento), ncol(df)) )
colnames(para_juntar) <-  colnames(df)
para_juntar$Departamento <- rep(levels(df$Departamento), each=empty_bar)

# juntamos las columnas creadas arriba
df <- rbind(df, para_juntar)

# ordenamos por departamento
df <- df %>% arrange(Departamento, PET)

# secuencia de todas las provincias
df$id <- seq(1, nrow(df))

# Nombre y posición para las etiquetas
label_df <- df
num_de_barras <- nrow(label_df)
angle <-  90 - 360 * (label_df$id-0.5) /num_de_barras 
label_df$hjust <- ifelse( angle < -90, 1, 0)
label_df$angle <- ifelse(angle < -90, angle + 180, angle)


# líneas base
base_df <- df %>% 
  group_by(Departamento) %>% 
  summarize(start = min(id), end=max(id) - empty_bar) %>% 
  rowwise() %>% 
  mutate(title = mean(c(start, end)))

# grids
grid_df <-  base_df
grid_df$end <-  grid_df$end[ c( nrow(grid_df), 1:nrow(grid_df)-1)] + 1
grid_df$start <-  grid_df$start - 1
grid_df <- grid_df[-1,]


# Gráfico
plot <-  ggplot(df, aes(x = as.factor(id), y = PET, fill = Departamento)) + 
  geom_bar(aes(x=as.factor(id), y=PET, fill=Departamento),stat="identity", alpha=0.5) +
  geom_segment(data=grid_df, aes(x = end, y = 80, xend = start, yend = 80), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
  geom_segment(data=grid_df, aes(x = end, y = 60, xend = start, yend = 60), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
  geom_segment(data=grid_df, aes(x = end, y = 40, xend = start, yend = 40), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
  geom_segment(data=grid_df, aes(x = end, y = 20, xend = start, yend = 20), colour = "grey", alpha=1, size=0.3 , inherit.aes = FALSE ) +
  annotate("text", x = rep(max(df$id),4), y = c(20, 40, 60, 80), label = c("20", "40", "60", "80") , color="darkgrey", size=1 , angle=0, fontface="bold", hjust=1) +
  ylim(-100,185) +
  labs(title = "Porcentaje de población en edad de trabajar (15-65 años) por provincia y departamento",
       subtitle = "Perú. 2015",
       caption = "Fuente: INEI") +
  scale_fill_viridis(discrete=TRUE) +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    plot.margin = unit(rep(-1,4), "cm")) +
  coord_polar() + 
  geom_text(data=label_df, aes(x=id, y=PET + 10, label=Provincia, hjust=hjust), 
            color="black", 
            fontface="bold",
            alpha=0.6, size=1, 
            angle= label_df$angle, 
            inherit.aes = FALSE )  +
  geom_segment(data=base_df, aes(x = start, y = -5, xend = end, yend = -5), colour = "darkgrey", alpha=0.8, size=0.6 , inherit.aes = FALSE ) +
  geom_text(data=base_df, aes(x = title, y = 185, label=Departamento), colour = "black", alpha=0.8, size=1.5, fontface="bold", inherit.aes = FALSE)



plot



```