Tarea2

Author

Luis Quesada

Carga de paquetes

library(tidyverse)
library(plotly)
library(DT)
library(scales)
library(ggthemes)

Carga de datos

paises <- read_csv(
  "https://raw.githubusercontent.com/sigenr/2025-i/refs/heads/main/datos/natural-earth/paises.csv"
)

Gráficos con ggplot2

# Gráfico de dispersión de PIB per cápita vs esperanza de vida al nacer
# coloreado por continente
paises |>
  ggplot(aes(x = GDP_PC, y = LIFE_EXPECTANCY, color = CONTINENT)) +
  geom_point() +
  scale_x_continuous(labels = comma, limits = c(0, NA))

paises |>
  filter(CONTINENT == 'North America' | CONTINENT == 'Europe') |>
  ggplot(aes(x = GDP_PC, y = LIFE_EXPECTANCY, color = CONTINENT)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(labels = comma, limits = c(0, NA)) +
  scale_y_continuous(labels = comma, limits = c(50, 90))

# Gráfico de dispersión de PIB per cápita vs esperanza de vida al nacer
# en África y Europa coloreado por continente
# + curva de tendencia
paises |>
  filter(CONTINENT == 'North America' | CONTINENT == 'South America') |>
  ggplot(aes(x = GDP_PC, y = LIFE_EXPECTANCY, color = CONTINENT)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(labels = comma, limits = c(0, NA)) +
  scale_y_continuous(labels = comma, limits = c(50, 90)) +
  ggtitle("PIB per cápita vs esperanza de vida al nacer por continente") +
  xlab("PIB per cápita  (USD)") +
  ylab("Esperanza de vida (años)") +
  labs(subtitle = "Datos de África y Europa", 
       caption = "Fuentes: Natural Earth y Banco Mundial",
       color = "Continente") +
  theme_economist() # estilo de ggthemes
`geom_smooth()` using method = 'loess' and formula = 'y ~ x'

Uso de graficos interactivos con ploty

# Gráfico de dispersión PIB per cápita vs esperanza de vida
grafico_dispersion_ggplot2 <-
  paises |>
  ggplot(aes(x = GDP_PC, y = LIFE_EXPECTANCY, color = CONTINENT)) +
  geom_point(aes(
    text = paste0(
      "País: ",
      NAME,
      "\n",
      "PIB per cápita: ",
      scales::comma(round(GDP_PC, 2)),
      "\n",
      "Esperanza de vida: ",
      round(LIFE_EXPECTANCY, 2)
    )
  )) +
  geom_smooth(method = "lm") +
  scale_x_continuous(labels = comma, limits = c(0, NA)) +
  scale_y_continuous(labels = comma, limits = c(50, 90)) +
  ggtitle("PIB per cápita vs esperanza de vida al nacer") +
  xlab("PIB per cápita (USD)") +
  ylab("Esperanza de vida (años)") +
  labs(caption = "Fuentes: Natural Earth y Banco Mundial", color = "Continente") +
  theme_economist()  
Warning in geom_point(aes(text = paste0("País: ", NAME, "\n", "PIB per cápita:
", : Ignoring unknown aesthetics: text
# Gráfico de dispersión plotly
ggplotly(grafico_dispersion_ggplot2, tooltip = "text") |>
  config(locale = 'es')
`geom_smooth()` using formula = 'y ~ x'
Warning: Removed 11 rows containing non-finite outside the scale range
(`stat_smooth()`).