Cargar paquetes
library(sf)
## Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.3.3
## āā Attaching core tidyverse packages āāāāāāāāāāāāāāāāāāāāāāāā tidyverse 2.0.0 āā
## ā dplyr 1.1.3 ā readr 2.1.4
## ā forcats 1.0.0 ā stringr 1.5.0
## ā ggplot2 3.5.1 ā tibble 3.2.1
## ā lubridate 1.9.3 ā tidyr 1.3.0
## ā purrr 1.0.2
## āā Conflicts āāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāāā tidyverse_conflicts() āā
## ā dplyr::filter() masks stats::filter()
## ā dplyr::lag() masks stats::lag()
## ā¹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(patchwork)
## Warning: package 'patchwork' was built under R version 4.3.3
Cargar y visualizar datos
#cargar datos
# voy a cargar una capa por defecto que tiene la paqueterĆa sf
data<-sf::read_sf(system.file("gpkg/nc.gpkg", package = "sf"))
#Visualizacion de los datos
data |>
ggplot()+
geom_sf(data=data)

Generar clasificaciones de las variables
# Intervalos
# El argumento style, permite diferentes categorizaciones. Fixed permite hacerlo de una manera manual
# Primera variable
x=classInt::classIntervals(data$BIR74,n=4,style = "fixed",
fixedBreaks=c(0, 5000, 10000, 15000, 22000))
x
## style: fixed
## one of 156,849 possible partitions of this variable into 4 classes
## [0,5000) [5000,10000) [10000,15000) [15000,22000]
## 84 10 3 3
# Segunda variable
y=classInt::classIntervals(data$SID74,3,style = "fixed",
fixedBreaks=c(0, 2, 4, 7, 50))
y
## style: fixed
## one of 1,540 possible partitions of this variable into 4 classes
## [0,2) [2,4) [4,7) [7,50]
## 24 14 28 34
# unimos las categorizaciones al shape de los datos
data$x = classInt::findCols(x)
data$y = classInt::findCols(y)
# Estas dos columnas permiten organizar las combinaciones de colores, de tal manera que se diferencien entre si
data$alpha = as.character(data$x + data$y)
data$color = as.character(atan(data$y/data$x))
Generación del mapa bivariado
map<-
ggplot()+
geom_sf(data = data,aes(fill=color, alpha=alpha),shape=15, size=11,show.legend = F, lwd=0)+
scale_fill_viridis_d(option="inferno")+
theme_void()
map
## Warning: Using alpha for a discrete variable is not advised.

Generación de la leyenda
leg<-
ggplot(expand.grid(x=1:4,y=1:4), aes(x,y))+
geom_tile(aes(alpha=x+y,fill=atan(y/x)))+
scale_fill_viridis_c(option="inferno")+
labs(x="BIR74", y="SID74")+
theme(legend.position="none",
axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.ticks = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank())+
coord_equal()
leg

Unimos la leyenda y el mapa en una sola figura
map + inset_element(leg, 0,0,0.4,0.4)
## Warning: Using alpha for a discrete variable is not advised.
