# Instalar el paquete ggplot2 si no está instalado
if (!requireNamespace("ggplot2", quietly = TRUE)) {
  install.packages("ggplot2")
}

# Cargar el paquete ggplot2
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.2.3
# Parámetros
p1 <- 3
p2 <- 2
m <- 20

# Función de utilidad
U <- function(x1, x2) {
  return(x1 + x2)
}

# Restricción presupuestaria
x2_restriccion <- function(x1) {
  return((m - p1 * x1) / p2)
}

# Crear una grilla de posibles combinaciones de x1 y x2
x1 <- seq(0, m / p1, length.out = 100)
x2 <- seq(0, m / p2, length.out = 100)
grid <- expand.grid(x1 = x1, x2 = x2)

# Calcular utilidad y restricción presupuestaria
grid$U <- with(grid, U(x1, x2))
grid$x2_restriccion <- with(grid, x2_restriccion(x1))

# Crear niveles de utilidad para las curvas de indiferencia
levels <- seq(min(grid$U, na.rm = TRUE), max(grid$U, na.rm = TRUE), length.out = 6)

# Graficar
ggplot(grid) +
  geom_tile(aes(x = x1, y = x2, fill = U)) +
  geom_line(aes(x = x1, y = x2_restriccion), color = "red", linetype = "dashed", size = 1) +
  geom_contour(aes(x = x1, y = x2, z = U, color = ..level..), breaks = levels, size = 1) +
  scale_fill_gradient2(low = "blue", mid = "white", high = "orange", midpoint = median(grid$U)) +
  labs(x = "x1", y = "x2", fill = "Utilidad", color = "Curvas de\nindiferencia") +
  theme_minimal()
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## Warning: The dot-dot notation (`..level..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(level)` instead.