# =============================================================================
# Dashboards interactivos Gapminder 1952–2007
# Perú frente a Latinoamérica y los países andinos
# Autor: Flores Velazque, Jorge Rubén
# Curso: Herramientas Informáticas · Docente: Joel Turco Quinto
# Ejecutar en RStudio: botón "Run App" o shiny::runApp("shiny_gapminder")
# =============================================================================
library(shiny)
library(bslib)
library(dplyr)
library(ggplot2)
library(plotly)
library(DT)
library(gapminder)
# ---- 1. Datos y grupos de comparación ---------------------------------------
latam <- c("Argentina", "Bolivia", "Brazil", "Chile", "Colombia", "Costa Rica",
"Cuba", "Dominican Republic", "Ecuador", "El Salvador", "Guatemala",
"Haiti", "Honduras", "Jamaica", "Mexico", "Nicaragua", "Panama",
"Paraguay", "Peru", "Puerto Rico", "Trinidad and Tobago", "Uruguay",
"Venezuela")
andinos <- c("Peru", "Bolivia", "Ecuador", "Colombia", "Venezuela", "Chile")
cont_es <- c(Africa = "África", Americas = "Américas", Asia = "Asia",
Europe = "Europa", Oceania = "Oceanía")
col_cont <- c("África" = "#D08C2E", "Américas" = "#C1121F", "Asia" = "#0F766E",
"Europa" = "#2E5C8A", "Oceanía" = "#7C6BA8")
col_and <- c(Peru = "#C1121F", Chile = "#0B1F3A", Ecuador = "#0F766E",
Colombia = "#2E5C8A", Venezuela = "#B7791F", Bolivia = "#8A8F98")
gm <- gapminder %>%
mutate(country = as.character(country),
continente = unname(cont_es[as.character(continent)]),
log_gdp = log10(gdpPercap))
anios <- sort(unique(gm$year))
var_lab <- c(lifeExp = "Esperanza de vida (años)",
gdpPercap = "PIB per cápita (USD ajustados por inflación)",
pop = "Población (habitantes)")
FUENTE <- "Fuente: Gapminder Foundation; paquete gapminder (Bryan, 2023). Elaboración propia en R."
# Curva de Preston: V = a + b·log10(G), estimada por MCO para un año
preston <- function(df) {
m <- lm(lifeExp ~ log_gdp, data = df)
list(a = coef(m)[[1]], b = coef(m)[[2]], r2 = summary(m)$r.squared,
r = cor(df$log_gdp, df$lifeExp),
rho = cor(df$gdpPercap, df$lifeExp, method = "spearman"), modelo = m)
}
num <- function(x, d = 1) formatC(x, format = "f", digits = d, big.mark = " ", decimal.mark = ",")
tema <- theme_minimal(base_size = 12) +
theme(plot.title = element_text(face = "bold", colour = "#0B1F3A"),
panel.grid.minor = element_blank(), legend.position = "top")
# Tablas DT en español, con coma decimal y espacio como separador de miles
dt_es <- list(search = "Buscar:", lengthMenu = "Mostrar _MENU_ filas",
info = "Filas _START_ a _END_ de _TOTAL_", infoEmpty = "Sin datos",
zeroRecords = "No hay coincidencias",
paginate = list(previous = "Anterior", `next` = "Siguiente"))
tabla <- function(df, dom = "t", filter = "none", ...) {
dt <- datatable(df, rownames = FALSE, filter = filter,
options = list(dom = dom, pageLength = 12, language = dt_es, ...))
decimales <- function(x) {
for (k in 0:2) if (all(abs(x * 10^k - round(x * 10^k)) < 1e-8, na.rm = TRUE)) return(k)
2
}
for (cc in names(df)[vapply(df, is.numeric, logical(1))]) {
if (cc %in% c("Año", "Rango vida", "Rango PIB")) next
dt <- formatRound(dt, cc, digits = decimales(df[[cc]]), dec.mark = ",", mark = " ")
}
dt
}
# ---- 2. Interfaz -------------------------------------------------------------
tema_app <- bs_theme(version = 5, bg = "#F7F6F2", fg = "#1E2A3A",
primary = "#0B1F3A", secondary = "#0F766E",
base_font = font_collection("Segoe UI", "Noto Sans", "Helvetica", "Arial", "sans-serif"),
heading_font = font_collection("Georgia", "Noto Serif", "serif"))
nota <- function(...) div(class = "small text-muted mt-2", ...)
selector_anio <- function(id, valor = 2007) {
sliderInput(id, "Año", min = 1952, max = 2007, value = valor, step = 5, sep = "",
animate = animationOptions(interval = 1200))
}
ui <- page_navbar(
title = "Gapminder · Perú 1952–2007",
theme = tema_app,
fillable = FALSE,
bg = "#0B1F3A",
inverse = TRUE,
header = tags$style(HTML("
.navbar .nav-link { font-size:.92rem; }
.navbar .nav-link.active { border-bottom:3px solid #7FD1C7; }
.card-header { font-weight:600; color:#0B1F3A; }
.bslib-value-box .value-box-value { font-family: Georgia, 'Noto Serif', serif; }
")),
# ---- Inicio ----
nav_panel("Inicio",
layout_columns(col_widths = c(3, 3, 3, 3),
value_box("Países", "142", theme = "primary", p("12 cortes quinquenales")),
value_box("Perú: esperanza de vida", "43,9 › 71,4", theme = "danger", p("+27,5 años, 1952–2007")),
value_box("Brecha con Latinoamérica", "–8,0 › –1,7", theme = "secondary", p("años; se cierra el 79 %")),
value_box("Brecha de PIB per cápita", "+427 › –1 104", theme = "warning", p("USD; negativa desde 1992"))
),
layout_columns(col_widths = c(7, 5),
card(card_header("Pregunta de investigación"),
p(class = "text-muted", strong("Curso: "), "Herramientas Informáticas · ", strong("Docente: "), "Joel Turco Quinto · ", strong("Autor: "), "Flores Velazque, Jorge Rubén"),
p("¿Convergió el Perú con su región en salud e ingreso entre 1952 y 2007?"),
tags$ul(
tags$li(strong("H1 · Convergencia sanitaria: "), "la brecha de esperanza de vida frente al promedio latinoamericano se reduce de forma sostenida."),
tags$li(strong("H2 · No convergencia económica: "), "el PIB per cápita pierde su ventaja inicial y termina bajo el promedio regional.")
),
p("Cada pestaña es un dashboard interactivo: cambie el año, los países o la variable y los gráficos, indicadores y tablas se recalculan en tiempo real.")
),
card(card_header("Fuente y grupos"),
p("Gapminder Foundation compila series de desarrollo de fuentes oficiales; el paquete ", code("gapminder"),
" (Bryan, 2023) ofrece un panel balanceado de 142 países × 12 años (1 704 observaciones)."),
tags$ul(
tags$li(strong("Latinoamérica: "), "23 países de las Américas, excepto EE. UU. y Canadá."),
tags$li(strong("Países andinos: "), "Perú, Bolivia, Ecuador, Colombia, Venezuela y Chile.")
),
nota("Diseño descriptivo-comparativo: las asociaciones no implican causalidad.")
)
)
),
# ---- D1 Curva de Preston ----
nav_panel("D1 · Ingreso y vida",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
selector_anio("d1_anio"),
checkboxGroupInput("d1_cont", "Continentes", choices = names(col_cont), selected = names(col_cont)),
checkboxInput("d1_log", "PIB en escala logarítmica", TRUE),
checkboxInput("d1_fit", "Mostrar curva de Preston (MCO)", TRUE),
selectizeInput("d1_pais", "Resaltar países", choices = sort(unique(gm$country)),
selected = "Peru", multiple = TRUE)
),
layout_columns(col_widths = c(3, 3, 3, 3),
value_box("r de Pearson (log PIB)", textOutput("d1_r"), theme = "secondary"),
value_box("R² del modelo", textOutput("d1_r2"), theme = "primary"),
value_box("β: años por ×10 de ingreso", textOutput("d1_b"), theme = "primary"),
value_box("Residuo del Perú", textOutput("d1_res"), theme = "danger")
),
card(full_screen = TRUE, card_header("Figura 1. Esperanza de vida y PIB per cápita"),
plotlyOutput("d1_plot", height = "520px"), nota(FUENTE, " Tamaño de burbuja = población.")),
card(card_header("Interpretación"), uiOutput("d1_txt"))
)
),
# ---- D2 Población ----
nav_panel("D2 · Población",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
selector_anio("d2_anio"),
checkboxGroupInput("d2_cont", "Continentes", choices = names(col_cont), selected = names(col_cont))
),
layout_columns(col_widths = c(4, 4, 4),
value_box("r de Pearson (log población)", textOutput("d2_r"), theme = "danger"),
value_box("ρ de Spearman", textOutput("d2_rho"), theme = "danger"),
value_box("Países analizados", textOutput("d2_n"), theme = "primary")
),
card(full_screen = TRUE, card_header("Figura 2. Esperanza de vida y población"),
plotlyOutput("d2_plot", height = "520px"), nota(FUENTE, " Tamaño de burbuja = PIB per cápita.")),
card(card_header("Interpretación"),
p("Si la correlación es cercana a cero, el tamaño demográfico no ordena a los países por esperanza de vida: el ingreso y las instituciones pesan más (Deaton, 2013). Compárese con D1."))
)
),
# ---- D3 Trayectoria de un país ----
nav_panel("D3 · Trayectoria",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
selectInput("d3_pais", "País", choices = sort(unique(gm$country)), selected = "Peru"),
radioButtons("d3_var", "Variable", choices = setNames(names(var_lab), var_lab), selected = "gdpPercap"),
sliderInput("d3_rango", "Periodo", min = 1952, max = 2007, value = c(1952, 2007), step = 5, sep = "")
),
layout_columns(col_widths = c(4, 4, 4),
value_box("Valor inicial › final", textOutput("d3_ini"), theme = "primary"),
value_box("Cambio en el periodo", textOutput("d3_cambio"), theme = "secondary"),
value_box("Peor quinquenio", textOutput("d3_peor"), theme = "danger")
),
card(full_screen = TRUE, card_header(textOutput("d3_tit")),
plotlyOutput("d3_plot", height = "430px"), nota(FUENTE)),
card(fill = FALSE, card_header("Serie de datos"), DTOutput("d3_tab", fill = FALSE))
)
),
# ---- D4 Brecha con Latinoamérica ----
nav_panel("D4 · Brecha regional",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
selectInput("d4_pais", "País latinoamericano", choices = sort(latam), selected = "Peru"),
radioButtons("d4_var", "Variable", choices = setNames(c("lifeExp", "gdpPercap"), var_lab[1:2])),
radioButtons("d4_prom", "Promedio regional",
choices = c("Aritmético (cada país pesa igual)" = "simple",
"Ponderado por población" = "pond")),
nota("Brecha Bₜ = valor del país − promedio de los 23 países latinoamericanos.")
),
layout_columns(col_widths = c(4, 4, 4),
value_box("Brecha 1952", textOutput("d4_b52"), theme = "primary"),
value_box("Brecha 2007", textOutput("d4_b07"), theme = "secondary"),
value_box("Lectura", textOutput("d4_veredicto"), theme = "danger")
),
layout_columns(col_widths = c(6, 6),
card(full_screen = TRUE, card_header("Figura 4a. País frente al promedio regional"),
plotlyOutput("d4_lineas", height = "400px")),
card(full_screen = TRUE, card_header("Figura 4b. Brecha Bₜ por quinquenio"),
plotlyOutput("d4_barras", height = "400px"))
),
card(fill = FALSE, card_header("Tabla de brechas"), DTOutput("d4_tab", fill = FALSE), nota(FUENTE))
)
),
# ---- D5 Países andinos ----
nav_panel("D5 · Países andinos",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
checkboxGroupInput("d5_paises", "Países andinos", choices = andinos, selected = andinos),
radioButtons("d5_var", "Variable", choices = setNames(names(var_lab), var_lab)),
checkboxInput("d5_indice", "Índice base 1952 = 100", FALSE)
),
card(full_screen = TRUE, card_header("Figura 5. Evolución de los países andinos, 1952–2007"),
plotlyOutput("d5_plot", height = "460px"), nota(FUENTE)),
card(fill = FALSE, card_header("Indicadores 1952–2007"), DTOutput("d5_tab", fill = FALSE),
nota("ΔV = V₂₀₀₇ − V₁₉₅₂ · Crec. acumulado = G₂₀₀₇/G₁₉₅₂ − 1 · TCAC = (G₂₀₀₇/G₁₉₅₂)^(1/55) − 1"))
)
),
# ---- D6 Posición andina ----
nav_panel("D6 · Posición andina",
layout_sidebar(fillable = FALSE,
sidebar = sidebar(width = 280,
selector_anio("d6_anio"),
radioButtons("d6_var", "Ordenar por",
choices = c("Esperanza de vida" = "lifeExp", "PIB per cápita" = "gdpPercap",
"Residuo de Preston" = "residuo")),
nota("Residuo de Preston = vida observada − vida esperada según la curva mundial del mismo año (D1). Positivo = más salud de la que predice su ingreso.")
),
card(full_screen = TRUE, card_header(textOutput("d6_tit")),
plotlyOutput("d6_plot", height = "420px"), nota(FUENTE)),
card(fill = FALSE, card_header("Seis países andinos"), DTOutput("d6_tab", fill = FALSE))
)
),
# ---- Datos y metodología ----
nav_panel("Datos y método",
layout_columns(col_widths = c(7, 5),
card(card_header("Explorador de datos"),
DTOutput("datos"), downloadButton("descarga", "Descargar CSV filtrado")),
card(card_header("Metodología y referencias"),
tags$ol(
tags$li("Importar: ", code("library(gapminder)")),
tags$li("Transformar: ", code("filter(), group_by()")),
tags$li("Calcular: ", code("summarise(), mutate(), lm()")),
tags$li("Visualizar: ", code("ggplot2 + plotly::ggplotly()")),
tags$li("Interactuar: ", code("shiny"), " — los ", code("input$"), " recalculan ", code("reactive()"), " y ", code("render*()")),
tags$li("Publicar: ", code("rsconnect::deployApp()"), " en shinyapps.io")
),
tags$hr(),
tags$p(class = "small",
"Bloom, D. E., y Canning, D. (2000). The health and wealth of nations. ", em("Science, 287"), "(5456), 1207–1209.", br(),
"Bryan, J. (2023). ", em("gapminder: Data from Gapminder"), " [Paquete de R]. CRAN.", br(),
"Chang, W., et al. (2023). ", em("shiny: Web application framework for R"), " [Paquete de R]. CRAN.", br(),
"Deaton, A. (2013). ", em("The great escape"), ". Princeton University Press.", br(),
"Preston, S. H. (1975). The changing relation between mortality and level of economic development. ", em("Population Studies, 29"), "(2), 231–248.", br(),
"Rosling, H., Rosling, O., y Rosling Rönnlund, A. (2018). ", em("Factfulness"), ". Flatiron Books.", br(),
"Sen, A. (1999). ", em("Development as freedom"), ". Oxford University Press.", br(),
"Sievert, C. (2020). ", em("Interactive web-based data visualization with R, plotly, and shiny"), ". CRC Press.", br(),
"Wickham, H. (2016). ", em("ggplot2: Elegant graphics for data analysis"), " (2.ª ed.). Springer."
)
)
)
),
nav_spacer(),
nav_item(span(style = "color:#C9D3E0; font-size:.85rem;", "Flores Velazque, J. R. · Herramientas Informáticas · Docente: Joel Turco Quinto"))
)
# ---- 3. Servidor -------------------------------------------------------------
server <- function(input, output, session) {
# ===== D1 =====
d1 <- reactive({
req(input$d1_cont)
gm %>% filter(year == input$d1_anio, continente %in% input$d1_cont)
})
d1_mod <- reactive({ req(nrow(d1()) > 3); preston(d1()) })
output$d1_r <- renderText(num(d1_mod()$r, 2))
output$d1_r2 <- renderText(num(d1_mod()$r2, 2))
output$d1_b <- renderText(paste0("+", num(d1_mod()$b, 1)))
output$d1_res <- renderText({
pe <- d1() %>% filter(country == "Peru")
if (nrow(pe) == 0) return("—")
m <- d1_mod(); r <- pe$lifeExp - (m$a + m$b * pe$log_gdp)
paste0(ifelse(r >= 0, "+", ""), num(r, 1), " años")
})
output$d1_plot <- renderPlotly({
df <- d1(); m <- d1_mod()
df$etiqueta <- paste0("", df$country, "
Vida: ", num(df$lifeExp),
" años
PIB pc: ", num(df$gdpPercap, 0), " USD
Población: ",
num(df$pop / 1e6), " M")
p <- ggplot(df, aes(gdpPercap, lifeExp, size = pop, colour = continente, text = etiqueta)) +
geom_point(alpha = .65) +
scale_colour_manual(values = col_cont) + scale_size(range = c(2, 16), guide = "none") +
labs(x = "PIB per cápita (USD)", y = "Esperanza de vida (años)", colour = NULL) + tema
if (input$d1_log) p <- p + scale_x_log10(labels = scales::label_comma(big.mark = " "))
else p <- p + scale_x_continuous(labels = scales::label_comma(big.mark = " "))
if (input$d1_fit) {
g <- 10^seq(min(df$log_gdp), max(df$log_gdp), length.out = 100)
curva <- data.frame(gdpPercap = g, lifeExp = m$a + m$b * log10(g))
p <- p + geom_line(data = curva, aes(gdpPercap, lifeExp), inherit.aes = FALSE,
colour = "#0B1F3A", linewidth = .8, linetype = "dashed")
}
res <- df %>% filter(country %in% input$d1_pais)
if (nrow(res) > 0)
p <- p + geom_point(data = res, aes(gdpPercap, lifeExp), inherit.aes = FALSE,
shape = 21, size = 7, stroke = 1.4, colour = "#000000", fill = NA) +
geom_text(data = res, aes(gdpPercap, lifeExp, label = country), inherit.aes = FALSE,
nudge_y = 2.5, size = 4, fontface = "bold", colour = "#000000")
ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h", y = 1.08)) %>%
config(displaylogo = FALSE, locale = "es")
})
output$d1_txt <- renderUI({
m <- d1_mod()
p(sprintf("En %d, el modelo V = %s + %s·log₁₀(PIB) explica el %s %% de la variación de la esperanza de vida (R² = %s). Multiplicar por diez el ingreso se asocia con %s años más de vida: es la curva de Preston (1975), lineal en logaritmos y con rendimientos decrecientes en niveles. Use el control de año (▶) para ver cómo la curva se desplaza hacia arriba con el tiempo.",
input$d1_anio, num(m$a, 1), num(m$b, 1), num(100 * m$r2, 0), num(m$r2, 2), num(m$b, 1)))
})
# ===== D2 =====
d2 <- reactive({ req(input$d2_cont); gm %>% filter(year == input$d2_anio, continente %in% input$d2_cont) })
output$d2_r <- renderText(num(cor(log10(d2()$pop), d2()$lifeExp), 2))
output$d2_rho <- renderText(num(cor(d2()$pop, d2()$lifeExp, method = "spearman"), 2))
output$d2_n <- renderText(nrow(d2()))
output$d2_plot <- renderPlotly({
df <- d2()
df$etiqueta <- paste0("", df$country, "
Población: ", num(df$pop / 1e6), " M
Vida: ",
num(df$lifeExp), " años")
p <- ggplot(df, aes(pop, lifeExp, size = gdpPercap, colour = continente, text = etiqueta)) +
geom_point(alpha = .65) + scale_x_log10(labels = scales::label_number(scale = 1e-6, suffix = " M")) +
scale_colour_manual(values = col_cont) + scale_size(range = c(2, 14), guide = "none") +
labs(x = "Población (escala log)", y = "Esperanza de vida (años)", colour = NULL) + tema
ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h", y = 1.08)) %>% config(displaylogo = FALSE)
})
# ===== D3 =====
d3 <- reactive(gm %>% filter(country == input$d3_pais, between(year, input$d3_rango[1], input$d3_rango[2])))
output$d3_tit <- renderText(paste0("Figura 3. ", input$d3_pais, ": ", var_lab[[input$d3_var]]))
dec3 <- reactive(if (input$d3_var == "lifeExp") 1 else 0)
output$d3_ini <- renderText({
v <- d3()[[input$d3_var]]; if (input$d3_var == "pop") v <- v / 1e6
paste(num(first(v), dec3()), "›", num(last(v), dec3()), if (input$d3_var == "pop") "M" else "")
})
output$d3_cambio <- renderText({
v <- d3()[[input$d3_var]]; n <- last(d3()$year) - first(d3()$year)
if (input$d3_var == "lifeExp") paste0(ifelse(last(v) >= first(v), "+", ""), num(last(v) - first(v)), " años")
else paste0(num(100 * (last(v) / first(v) - 1), 0), " % (TCAC ", num(100 * ((last(v) / first(v))^(1 / max(n, 1)) - 1), 2), " %)")
})
output$d3_peor <- renderText({
df <- d3(); v <- df[[input$d3_var]]
if (length(v) < 2) return("—")
ch <- if (input$d3_var == "lifeExp") diff(v) else 100 * (v[-1] / v[-length(v)] - 1)
i <- which.min(ch)
paste0(df$year[i], "–", df$year[i + 1], ": ", ifelse(ch[i] >= 0, "+", ""), num(ch[i], 1),
if (input$d3_var == "lifeExp") " años" else " %")
})
output$d3_plot <- renderPlotly({
df <- d3(); df$y <- df[[input$d3_var]]
df$etiqueta <- paste0(df$year, ": ", num(df$y, dec3()))
p <- ggplot(df, aes(year, y, group = 1, text = etiqueta)) +
annotate("rect", xmin = 1987, xmax = 1992, ymin = -Inf, ymax = Inf, fill = "#B7791F", alpha = .12) +
geom_line(colour = "#C1121F", linewidth = 1.2) + geom_point(colour = "#C1121F", size = 2.5) +
scale_x_continuous(breaks = anios) + scale_y_continuous(labels = scales::label_comma(big.mark = " ")) +
labs(x = NULL, y = var_lab[[input$d3_var]]) + tema
ggplotly(p, tooltip = "text") %>% config(displaylogo = FALSE)
})
output$d3_tab <- renderDT({
d3() %>% transmute(Año = year, `Esperanza de vida` = round(lifeExp, 1),
`PIB per cápita` = round(gdpPercap), `Población (M)` = round(pop / 1e6, 2)) %>%
tabla()
})
# ===== D4 =====
d4 <- reactive({
v <- input$d4_var
reg <- gm %>% filter(country %in% latam) %>% group_by(year) %>%
summarise(prom = if (input$d4_prom == "simple") mean(.data[[v]]) else weighted.mean(.data[[v]], pop),
.groups = "drop")
gm %>% filter(country == input$d4_pais) %>% select(year, pais = all_of(v)) %>%
left_join(reg, by = "year") %>% mutate(brecha = pais - prom)
})
dec4 <- reactive(if (input$d4_var == "lifeExp") 1 else 0)
fmt_b <- function(x, d) paste0(ifelse(x > 0, "+", ""), num(x, d))
output$d4_b52 <- renderText(fmt_b(d4()$brecha[1], dec4()))
output$d4_b07 <- renderText(fmt_b(last(d4()$brecha), dec4()))
output$d4_veredicto <- renderText({
b <- d4()$brecha
if (abs(last(b)) < abs(b[1])) "Converge" else "Diverge"
})
output$d4_lineas <- renderPlotly({
df <- d4() %>% tidyr::pivot_longer(c(pais, prom), names_to = "serie", values_to = "valor") %>%
mutate(serie = ifelse(serie == "pais", input$d4_pais, "Promedio Latinoamérica (23)"),
etiqueta = paste0(serie, " ", year, ": ", num(valor, dec4())))
cols <- setNames(c("#C1121F", "#6B7280"), c(input$d4_pais, "Promedio Latinoamérica (23)"))
p <- ggplot(df, aes(year, valor, colour = serie, group = serie, text = etiqueta)) +
geom_line(linewidth = 1.1) + geom_point(size = 2) + scale_colour_manual(values = cols) +
scale_y_continuous(labels = scales::label_comma(big.mark = " ")) +
labs(x = NULL, y = var_lab[[input$d4_var]], colour = NULL) + tema
ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h", y = 1.12)) %>% config(displaylogo = FALSE)
})
output$d4_barras <- renderPlotly({
df <- d4() %>% mutate(signo = ifelse(brecha >= 0, "Sobre el promedio", "Bajo el promedio"),
etiqueta = paste0(year, ": ", fmt_b(brecha, dec4())))
p <- ggplot(df, aes(factor(year), brecha, fill = signo, text = etiqueta)) + geom_col() +
geom_hline(yintercept = 0, colour = "#1E2A3A") +
scale_fill_manual(values = c("Sobre el promedio" = "#0F766E", "Bajo el promedio" = "#C1121F")) +
labs(x = NULL, y = "Brecha Bₜ", fill = NULL) + tema
ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h", y = 1.12)) %>% config(displaylogo = FALSE)
})
output$d4_tab <- renderDT({
d4() %>% transmute(Año = year, País = round(pais, dec4()), `Promedio regional` = round(prom, dec4()),
`Brecha Bₜ` = round(brecha, dec4() + 1)) %>%
tabla() %>%
formatStyle("Brecha Bₜ", color = styleInterval(0, c("#C1121F", "#0F766E")), fontWeight = "bold")
})
# ===== D5 =====
output$d5_plot <- renderPlotly({
req(input$d5_paises); v <- input$d5_var
df <- gm %>% filter(country %in% input$d5_paises) %>% group_by(country) %>% arrange(year) %>%
mutate(y = if (input$d5_indice) 100 * .data[[v]] / first(.data[[v]]) else .data[[v]]) %>% ungroup() %>%
mutate(etiqueta = paste0(country, " ", year, ": ", num(y, ifelse(v == "lifeExp" || input$d5_indice, 1, 0))))
p <- ggplot(df, aes(year, y, colour = country, group = country, text = etiqueta)) +
geom_line(aes(linewidth = country == "Peru")) + geom_point(size = 1.6) +
scale_linewidth_manual(values = c(`TRUE` = 1.8, `FALSE` = .9), guide = "none") +
scale_colour_manual(values = col_and) + scale_x_continuous(breaks = anios) +
scale_y_continuous(labels = scales::label_comma(big.mark = " ")) +
labs(x = NULL, y = if (input$d5_indice) "Índice (1952 = 100)" else var_lab[[v]], colour = NULL) + tema
ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h", y = 1.1)) %>% config(displaylogo = FALSE)
})
output$d5_tab <- renderDT({
req(input$d5_paises)
gm %>% filter(country %in% input$d5_paises, year %in% c(1952, 2007)) %>% group_by(country) %>%
summarise(`Vida 1952` = round(lifeExp[year == 1952], 1), `Vida 2007` = round(lifeExp[year == 2007], 1),
`ΔV (años)` = round(lifeExp[year == 2007] - lifeExp[year == 1952], 1),
`PIB pc 1952` = round(gdpPercap[year == 1952]), `PIB pc 2007` = round(gdpPercap[year == 2007]),
`Crec. acumulado (%)` = round(100 * (gdpPercap[year == 2007] / gdpPercap[year == 1952] - 1), 1),
`TCAC (%)` = round(100 * ((gdpPercap[year == 2007] / gdpPercap[year == 1952])^(1 / 55) - 1), 2),
.groups = "drop") %>%
arrange(desc(`ΔV (años)`)) %>% rename(País = country) %>%
tabla() %>%
formatStyle("País", target = "row", backgroundColor = styleEqual("Peru", "#F8E1E3"))
})
# ===== D6 =====
d6 <- reactive({
mundo <- gm %>% filter(year == input$d6_anio); m <- preston(mundo)
mundo %>% filter(country %in% andinos) %>%
mutate(esperada = m$a + m$b * log_gdp, residuo = lifeExp - esperada)
})
etiqueta6 <- c(lifeExp = "Esperanza de vida (años)", gdpPercap = "PIB per cápita (USD)",
residuo = "Residuo de Preston (años)")
output$d6_tit <- renderText(paste0("Figura 6. Países andinos ", input$d6_anio, ": ", etiqueta6[[input$d6_var]]))
output$d6_plot <- renderPlotly({
df <- d6(); df$y <- df[[input$d6_var]]
d <- if (input$d6_var == "gdpPercap") 0 else 1
df$etiqueta <- paste0(df$country, ": ", num(df$y, d))
p <- ggplot(df, aes(reorder(country, y), y, fill = country == "Peru", text = etiqueta)) +
geom_col(width = .65) + coord_flip() +
geom_text(aes(y = y + sign(y) * 0.06 * max(abs(y)), label = num(y, d)), size = 4, colour = "#1E2A3A") +
scale_fill_manual(values = c(`TRUE` = "#C1121F", `FALSE` = "#8A9BB0"), guide = "none") +
scale_y_continuous(expand = expansion(mult = c(0.02, 0.15))) +
labs(x = NULL, y = etiqueta6[[input$d6_var]]) + tema
ggplotly(p, tooltip = "text") %>% layout(showlegend = FALSE) %>% config(displaylogo = FALSE)
})
output$d6_tab <- renderDT({
d6() %>% arrange(desc(lifeExp)) %>%
transmute(País = country, `Esperanza de vida` = round(lifeExp, 1),
`Rango vida` = rank(-lifeExp), `PIB per cápita` = round(gdpPercap),
`Rango PIB` = rank(-gdpPercap), `Población (M)` = round(pop / 1e6, 1),
`Vida esperada (Preston)` = round(esperada, 1), `Residuo` = round(residuo, 1)) %>%
tabla() %>%
formatStyle("País", target = "row", backgroundColor = styleEqual("Peru", "#F8E1E3"))
})
# ===== Datos =====
output$datos <- renderDT({
gm %>% transmute(País = country, Continente = continente, Año = year,
`Esperanza de vida` = round(lifeExp, 1), `PIB per cápita` = round(gdpPercap),
Población = pop) %>%
tabla(dom = "lftip", filter = "top", pageLength = 10, scrollX = TRUE)
})
output$descarga <- downloadHandler(
filename = function() "gapminder_filtrado.csv",
content = function(file) {
filas <- input$datos_rows_all
df <- gm %>% select(country, continente, year, lifeExp, gdpPercap, pop)
if (!is.null(filas)) df <- df[filas, ]
write.csv(df, file, row.names = FALSE, fileEncoding = "UTF-8")
}
)
}
shinyApp(ui, server)