---
title: "Dashboard Appol"
author: "Jorge Gandara & María Escorcia"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: fill
source_code: embed
---
```{r setup, include=FALSE}
#Librerías
library(flexdashboard)
library(readxl)
library(dplyr)
library(stringr)
library(tidyr)
library(ggplot2)
library(plotly)
library(highcharter)
library(DT)
library(janitor)
library(sf)
library(rnaturalearth)
library(scales)
#Ruta al archivo
archivo <- "Appol Datos.xlsx"
# ----- Transformación de datos -----
datos <- read_excel(archivo, sheet = "Tabla Datos") %>%
select(Periodo, `Tipo Producto`, Region, Ingresos, Gastos) %>%
mutate(
codigo_pais = str_sub(Region, 1, 3),
continente = str_extract(Region, '(?<= - ).+?(?=/)'),
pais = str_extract(Region, '(?<=/).*'),
trimestre = str_replace(str_extract(Periodo, 'Q[1-4]'), 'Q', 'T'),
anio = as.integer(str_extract(Periodo, '\\d{4}')),
utilidad = Ingresos - Gastos,
m_utilidad = ifelse(is.finite(utilidad / Ingresos),
utilidad / Ingresos, NA_real_)
)
tabla_productos <- read_excel(archivo, sheet = "Tabla Productos") %>%
clean_names()
datos <- datos %>%
left_join(tabla_productos, by = c('Tipo Producto' = 'tipo_producto')) %>%
clean_names()
```
Column {data-width=250}
-----------------------------------------------------------------------
### **M.Utilidad Total**
```{r}
valueBox(
sprintf("$ %.2f mill.", sum(datos$utilidad)/1e6),
caption = "M.Utilidad",
color = "#EEE8CD",
icon = "fa-apple"
)
```
### **M. Margen Global**
```{r}
margen_pct <- sum(datos$utilidad) / sum(datos$ingresos) * 100
valueBox(
sprintf("%.2f %%", margen_pct),
caption = "M.Margen",
color = "#FFF8DC",
icon = "fa-apple"
)
```
### M.Utilidad Top‑10 Países
```{r}
top_paises <- datos %>%
group_by(pais) %>%
summarise(
m_utilidad = sum(utilidad),
m_margen = sum(utilidad) / sum(ingresos)
) %>%
arrange(desc(m_utilidad)) %>%
slice_head(n = 10)
# Guardamos el rango numérico antes de formatear
rango_margen <- range(top_paises$m_margen, na.rm = TRUE)
# Ahora formateamos para la visualización
top_paises <- top_paises %>%
mutate(
m_utilidad = dollar(m_utilidad),
m_margen = percent(m_margen, accuracy = 0.1)
)
datatable(
top_paises,
rownames = FALSE,
options = list(dom = 'tp', pageLength = 10),
colnames = c("País", "M.Utilidad", "M.Margen")
) %>%
formatCurrency('m_utilidad', currency = "$", digits = 0) %>%
formatPercentage('m_margen', digits = 1) %>%
formatStyle(
'm_margen',
background = styleColorBar(rango_margen, '#FFE4E1'),
backgroundSize = '100% 80%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center'
)
```
Column {data-width=450}
-----------------------------------------------------------------------
### M.Utilidad por Año, Trimestre y Continente
```{r}
serie <- datos %>%
mutate(periodo = paste(trimestre, anio)) %>%
group_by(periodo, continente) %>%
summarise(m_utilidad = sum(utilidad), .groups = 'drop') # <- solo sumar utilidad
serie$periodo <- factor(serie$periodo, levels = unique(serie$periodo))
# Graficamos
ggplotly(
ggplot(serie, aes(x = periodo, y = m_utilidad, color = continente, group = continente)) +
geom_line(size = 1) +
geom_point() +
scale_y_continuous(labels = dollar_format(prefix = "$ ", suffix = " mill.", scale = 1e-6)) + # <- Formato de dinero en millones
scale_color_manual(values = c("América" = "#9F79EE",
"Asia" = "#FFE4E1",
"Europa" = "#63B8FF",
"África" = "#4876FF",
"Oceanía" = "#FF3E96")) +
labs(x = "Trimestre", y = "Suma de Utilidad Total",
title = "M. Utilidad Total por Año, Trimestre y Continente") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
legend.title = element_blank())
)
```
### M.Utilidad por País y Continente
```{r}
# Cargar las bibliotecas necesarias
library(highcharter)
library(dplyr)
library(sf)
library(rnaturalearth)
# Coordenadas de referencia
world <- ne_countries(returnclass = "sf") %>%
st_make_valid() %>%
select(iso_a3, geometry)
coords <- st_point_on_surface(world) %>%
mutate(longitude = st_coordinates(geometry)[,1],
latitude = st_coordinates(geometry)[,2]) %>%
st_drop_geometry()
# 'datos' es el dataframe con los datos de utilidad
map_data <- datos %>%
group_by(codigo_pais, pais, continente) %>%
summarise(utilidad = sum(utilidad), .groups = 'drop') %>%
left_join(coords, by = c("codigo_pais" = "iso_a3")) %>%
filter(!is.na(longitude))
# Definir paleta exacta de colores por continente según la imagen
paleta <- c(
"África" = "#4876FF", # Azul intenso para África
"América" = "#9F79EE", # Púrpura para América
"Asia" = "#FF8B8B", # Rosa/rojo claro para Asia
"Europa" = "#63B8FF", # Azul claro para Europa
"Oceanía" = "#FF83FA" # Rosa para Oceanía
)
# Coordenadas para las etiquetas de continentes
continent_labels <- data.frame(
name = c("AMÉRICA DEL NORTE", "AMÉRICA DEL SUR", "EUROPA", "ÁFRICA", "ASIA", "OCEANÍA"),
lat = c(45, -15, 50, 5, 40, -20),
lon = c(-100, -60, 10, 20, 100, 150)
)
# Coordenadas para las etiquetas de océanos
ocean_labels <- data.frame(
name = c("Océano Pacífico", "Océano Atlántico", "Océano Índico"),
lat = c(20, 30, -20),
lon = c(-150, -40, 80)
)
# Crear el mapa
map <- hcmap("custom/world",
data = map_data,
joinBy = c("iso_a3", "codigo_pais"),
showInLegend = FALSE,
nullColor = "#E0E0E0") %>%
hc_title(text = "Suma de Utilidad Total por País y Continente") %>%
hc_legend(
enabled = TRUE,
layout = "horizontal",
align = "center",
verticalAlign = "top",
itemStyle = list(fontSize = "12px"),
symbolWidth = 12,
symbolHeight = 12
) %>%
{
m <- .
# Añadir las series de burbujas por continente
for(cont in names(paleta)) {
df <- map_data %>% filter(continente == cont)
if(nrow(df) > 0) {
m <- m %>% hc_add_series(
df,
type = "mapbubble",
name = cont,
color = paleta[[cont]],
hcaes(lat = latitude, lon = longitude, z = utilidad),
maxSize = "10%",
showInLegend = TRUE,
marker = list(
fillOpacity = 0.6,
lineWidth = 1,
lineColor = "white"
)
)
}
}
# Añadir las etiquetas de continentes
for(i in 1:nrow(continent_labels)) {
m <- m %>% hc_add_series(
data = list(list(
lat = continent_labels$lat[i],
lon = continent_labels$lon[i],
name = continent_labels$name[i]
)),
type = "mappoint",
name = continent_labels$name[i],
showInLegend = FALSE,
enableMouseTracking = FALSE,
marker = list(enabled = FALSE),
dataLabels = list(
enabled = TRUE,
format = continent_labels$name[i],
style = list(
fontWeight = "bold",
color = "black",
textOutline = "none",
fontSize = "12px"
)
)
)
}
# Añadir las etiquetas de océanos
for(i in 1:nrow(ocean_labels)) {
m <- m %>% hc_add_series(
data = list(list(
lat = ocean_labels$lat[i],
lon = ocean_labels$lon[i],
name = ocean_labels$name[i]
)),
type = "mappoint",
name = ocean_labels$name[i],
showInLegend = FALSE,
enableMouseTracking = FALSE,
marker = list(enabled = FALSE),
dataLabels = list(
enabled = TRUE,
format = ocean_labels$name[i],
style = list(
fontStyle = "italic",
color = "#104E8B", # Azul oscuro para los océanos
textOutline = "none",
fontSize = "12px"
)
)
)
}
m
} %>%
hc_colorAxis(enabled = FALSE) %>%
hc_mapNavigation(
enabled = TRUE,
buttonOptions = list(verticalAlign = "bottom")
) %>%
hc_tooltip(
headerFormat = "",
pointFormat = "<b>{point.pais}</b><br>Utilidad: ${point.utilidad:,.0f}"
) %>%
hc_credits(
enabled = TRUE,
text = "© 2023 TechSoft, © 2023 Microsoft Corporation, Datos Appol",
style = list(fontSize = "10px")
) %>%
hc_chart(
backgroundColor = "#FFFFFF",
map = list(
backgroundColor = "#D6EBFF" # Color azul claro para los océanos
)
) %>%
hc_exporting(enabled = TRUE)
map
```
Column {data-width=300}
-----------------------------------------------------------------------
### M.Utilidad por Continente
```{r}
cont <- datos %>%
group_by(continente) %>%
summarise(utilidad = sum(utilidad), .groups = 'drop')
# Vector de colores por continente
colores_continentes <- c("América" = "#9F79EE",
"Asia" = "#FFE4E1",
"Europa" = "#63B8FF",
"África" = "#4876FF",
"Oceanía" = "#FF3E96")
# Extraer los colores en el orden que aparecen los continentes en tus datos
colores_ordenados <- colores_continentes[cont$continente]
plot_ly(
cont, labels = ~continente, values = ~utilidad,
type = 'pie', hole = 0.45,
textinfo = 'label+percent',
marker = list(colors = colores_ordenados)
) %>% layout(showlegend = TRUE)
```
### M.Utilidad por Categoría Producto
```{r}
categoria_producto <- datos %>%
group_by(categoria_producto) %>%
summarise(utilidad = sum(utilidad), .groups = 'drop')
hchart(categoria_producto,
"treemap",
hcaes(name = categoria_producto, value = utilidad))
```
### M.Utilidad por Tipo Producto
```{r}
tipo_prod <- datos %>%
group_by(tipo_producto) %>%
summarise(utilidad = sum(utilidad), .groups = 'drop')
hchart(tipo_prod,
"treemap",
hcaes(name = tipo_producto, value = utilidad))
```