La base de datos ha sido consultada en la pagina de datos abiertos del gobierno de Colombia durante el mes de Noviembre del año 2018. Los datos contienen las de precipitaciones y temperatura promediadas de cada mes, durante 30 años.
Por ejemplo, la variable septemp30a
contiene la temperatura promedio de 30 años, registrada para el mes de septiembre durante esos 30 años..
Se aplicarán algunas funciones del paquete tidyverse entre otros paquetes para explorar el conjunto de datos y hacer la depuración pertinente con el objetivo de estructurar la información de forma tabular, y así hacer un análisis descriptivo de las variables, generando gráficos con la librería ggplot2
.
Primero cargamos el paquete tidyverse, el cual es un conjunto de paquetes que permiten el manejo de bases de datos de manera eficiente.
La función read_csv
lee el archivo de nuestro directorio de trabajo.
library(tidyverse)
<- read_csv(file = "PrecipitacionTemperaturaPromedio.csv") datos
La función skim de la librería skimr permite obtener un resumen de los datos y conocer de manera general la estructura de nuestros datos.
library(skimr)
skim(datos)
── Data Summary ────────────────────────
Values
Name datos
Number of rows 450
Number of columns 41
_______________________
Column type frequency:
character 7
numeric 34
________________________
Group variables None
── Variable type: character ─────────────────────────────────────────
skim_variable n_missing complete_rate min max empty n_unique
1 nombre 0 1 4 18 0 441
2 categoria 0 1 2 2 0 5
3 departamento 0 1 4 30 0 32
4 municipio 0 1 4 27 0 342
5 corriente 0 1 3 16 0 326
6 lac 0 1 1 1 0 2
7 loc 0 1 1 1 0 1
whitespace
1 0
2 0
3 0
4 0
5 0
6 0
7 0
── Variable type: numeric ───────────────────────────────────────────
skim_variable n_missing complete_rate mean sd
1 codigo 0 1 26965458. 10733727.
2 lag 0 1 5.11 2.74
3 lam 0 1 28.2 17.1
4 las 0 1 27.1 18.3
5 log 0 1 74.2 1.68
6 lom 0 1 29.7 17.5
7 los 0 1 26.7 19.7
8 altitud 0 1 1078. 975.
9 enepreci30a 0 1 88.5 98.1
10 febpreci30a 0 1 98.5 85.2
11 marpreci30a 0 1 138. 96.3
12 abrpreci30a 0 1 205. 122.
13 maypreci30a 0 1 230. 140.
14 junpreci30a 0 1 182. 145.
15 julpreci30a 0 1 165. 143.
16 agopreci30a 0 1 164. 140.
17 seppreci30a 0 1 190. 133.
18 octpreci30a 0 1 232. 129.
19 novpreci30a 0 1 200. 121.
20 dicpreci30a 0 1 129. 112.
21 totalpreci30a 0 1 2005. 1279.
22 enetemp30a 0 1 22.2 5.59
23 febtemp30a 0 1 22.5 5.63
24 martemp30a 0 1 22.5 5.59
25 abrtemp30a 0 1 22.4 5.47
26 maytemp30a 0 1 22.3 5.41
27 juntemp30a 0 1 22.2 5.53
28 jultemp30a 0 1 22.2 5.71
29 agotemp30a 0 1 22.3 5.72
30 septemp30a 0 1 22.3 5.58
31 octtemp30a 0 1 22.1 5.43
32 novtemp30a 0 1 22.0 5.38
33 dictemp30a 0 1 22.0 5.45
34 protemp30a 0 1 22.2 5.53
p0 p25 p50 p75 p100 hist
1 11025010 21187575 24035095 29045118. 57025010 ▂▇▂▁▁
2 0 3 5 7 13 ▃▇▃▃▁
3 0 13 28 44 59 ▇▇▇▆▆
4 0 12 26.4 43.7 59.4 ▇▇▆▆▆
5 67 73 74 75 81 ▁▂▇▂▁
6 0 14 30 45 59 ▇▇▇▇▇
7 0 7.62 27 43.6 59.7 ▇▃▅▅▅
8 1 163. 966. 1850 4150 ▇▃▃▂▁
9 0.8 28.2 63 104. 619. ▇▁▁▁▁
10 0.5 43.1 81.8 124. 575. ▇▂▁▁▁
11 1.2 73.9 122. 176. 607. ▇▆▁▁▁
12 6.9 120. 175 267. 819. ▇▆▂▁▁
13 27.3 129. 185. 301. 854. ▇▅▂▁▁
14 8.2 72.9 131. 242. 853. ▇▃▂▁▁
15 6.5 55.7 116. 224. 805. ▇▃▂▁▁
16 17.6 57.0 128. 225. 866. ▇▃▁▁▁
17 35.7 94.2 164. 241. 911. ▇▃▁▁▁
18 65.7 147. 203. 284. 882. ▇▅▁▁▁
19 53.5 119. 172. 243. 836. ▇▃▁▁▁
20 15.2 55.5 99.3 155. 810. ▇▂▁▁▁
21 326. 1170. 1573. 2550. 8051 ▇▅▁▁▁
22 4.4 17.9 23.9 27 30.4 ▁▂▃▃▇
23 4.6 18 24.2 27.2 30.5 ▁▂▃▃▇
24 4.8 18.1 24.0 27.3 30.9 ▁▂▃▃▇
25 5 18.2 23.8 27.2 30.2 ▁▂▃▅▇
26 5.1 18.0 23.8 27.1 29.7 ▁▂▃▃▇
27 4.9 18.0 23.6 27.2 29.9 ▁▂▃▆▇
28 4.5 17.8 23.7 27.2 30.1 ▁▂▃▆▇
29 4.5 17.8 24.0 27.4 30.3 ▁▂▃▆▇
30 4.4 18.0 24 27.1 29.9 ▁▂▃▃▇
31 4.4 17.9 23.4 26.8 29 ▁▂▃▃▇
32 4.4 17.8 23.4 26.8 29 ▁▂▃▃▇
33 4.5 17.8 23.6 26.8 29.7 ▁▂▃▃▇
34 4.6 18.0 23.8 27.2 29.8 ▁▂▃▃▇
Se tienen para esta base de datos 450 filas y 41 columnas, 7 columnas de clase character
y 34 de clase ǹumeric
. La dimensión de la base de datos también es posible obtenerla con la función dim()
.
dim(datos)
[1] 450 41
El resumen anterior nos arroja una idea del comportamiento de las variables además de entregar información acerca de los valores ausentes NA
, que para esta base de datos en particular no hay. Un histograma con la distribución de las variables es reperesentado en el resumen, el cual también representaremos a través de la librería ggplot2 para cada una de las variables.
Una rápida consulta de los valores NA también puede lograrse de la siguiente manera. Solicitamos con la función table()
el conteo de los valores NA a través de la función is.na()
.
table(is.na(datos))
FALSE
18450
datos
Estructuraremos una base de datos que contenga la información que consideremos relevante para el análisis o exploración de la información que deseamos hacer.
Estas acciones que se mencionan, se pueden ejecutar a través del operador %>%
conocido como tubería (pipe), que permite encadenar varios comandos o funciones para que se ejecuten uno seguido de otro.
Obtendremos un objeto llamado precip, que contiene las precipitaciones de los municipios por mes.
<- datos %>%
precip # seleccionar las variables
select(departamento, municipio, altitud:dicpreci30a) %>%
# pasar de formato largo a ancho
pivot_longer(cols = c(enepreci30a:dicpreci30a), names_to = "mes",
values_to = "precipitaciones") %>%
# editar nombres de la variable mes
mutate(mes = gsub(pattern = "enepreci30a", replacement = "enero", x = mes),
mes = gsub(pattern = "febpreci30a", replacement = "febrero", x = mes),
mes = gsub(pattern = "marpreci30a", replacement = "marzo", x = mes),
mes = gsub(pattern = "abrpreci30a", replacement = "abril", x = mes),
mes = gsub(pattern = "maypreci30a", replacement = "mayo", x = mes),
mes = gsub(pattern = "junpreci30a", replacement = "junio", x = mes),
mes = gsub(pattern = "julpreci30a", replacement = "julio", x = mes),
mes = gsub(pattern = "agopreci30a", replacement = "agosto", x = mes),
mes = gsub(pattern = "seppreci30a", replacement = "septiembre", x = mes),
mes = gsub(pattern = "octpreci30a", replacement = "octubre", x = mes),
mes = gsub(pattern = "novpreci30a", replacement = "noviembre", x = mes),
mes = gsub(pattern = "dicpreci30a", replacement = "diciembre", x = mes),
# convertir la variable mes en factor
mes = factor(x = mes, levels = c("enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre")))
precip
dim(precip)
[1] 5400 5
Obtendremos el objeto que contenga la información de las temperaturas de los municipios por mes.
<- datos %>%
tempe select(departamento, municipio, altitud, enetemp30a:dictemp30a) %>%
pivot_longer(cols = c(enetemp30a:dictemp30a), names_to = "mes",
values_to = "temperaturas") %>%
mutate(mes = gsub(pattern = "enetemp30a", replacement = "enero", x = mes),
mes = gsub(pattern = "febtemp30a", replacement = "febrero", x = mes),
mes = gsub(pattern = "martemp30a", replacement = "marzo", x = mes),
mes = gsub(pattern = "abrtemp30a", replacement = "abril", x = mes),
mes = gsub(pattern = "maytemp30a", replacement = "mayo", x = mes),
mes = gsub(pattern = "juntemp30a", replacement = "junio", x = mes),
mes = gsub(pattern = "jultemp30a", replacement = "julio", x = mes),
mes = gsub(pattern = "agotemp30a", replacement = "agosto", x = mes),
mes = gsub(pattern = "septemp30a", replacement = "septiembre", x = mes),
mes = gsub(pattern = "octtemp30a", replacement = "octubre", x = mes),
mes = gsub(pattern = "novtemp30a", replacement = "noviembre", x = mes),
mes = gsub(pattern = "dictemp30a", replacement = "diciembre", x = mes),
mes = factor(x = mes, levels = c("enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre")))
tempe
dim(tempe)
[1] 5400 5
Uniremos los dos objetos que creamos para consolidar una única base de datos que contenga los datos de precipitación y temperatura. Las función right_join()
permite unir columnas a la base de datos, en este caso a la derecha de nuestro arreglo tabular para agregar la columna con las temperaturas.
<- right_join(x = precip, y = tempe) df_pretem
df_pretem
Se editarán los nombres de algunos departamentos que presentan errores de ortografía para presentarlos de manera correcta.
Se obtendrá una nueva columna con las regiones naturales de Colombia a la que pertenecen los diferentes departamentos, conformadas de la siguiente manera:
Región Pacífico : Cauca , Chocó, Nariño, Valle del Cauca
Región Orinoquía : Arauca, Casanare, Meta, Vichada
Región Amazonía : Amazonas, Caquetá, Guainía, Guaviare, Putumayo. (El departamento de Vaupés no aparece en los datos originales, por lo tanto no aparece aquí representado).
Región Caribe : Atlántico, Bolívar, Cesar, Cordoba, La Guajira, Magdalena, San Andrés Providencia y Santa Catalina, Sucre.
Región Andina : Antioquia, Boyacá, Caldas, Cundinamarca, Huila, Norte de Santander, Quindío, Risaralda, Santander, Tolima, Bogotá DC.
La región insular no se presenta en los datos. Región a la cual pertenece San Andrés, Providencia y Santa Catalina.
<- df_pretem %>%
df_pretem mutate(departamento = gsub(pattern = "Atlantico", replacement = "Atlántico", x = departamento),
departamento = gsub(pattern = "Bogota DC", replacement = "Bogotá DC", x = departamento),
departamento = gsub(pattern = "Bolivar", replacement = "Bolívar", x = departamento),
departamento = gsub(pattern = "Boyaca", replacement = "Boyacá", x = departamento),
departamento = gsub(pattern = "Caqueta", replacement = "Caquetá", x = departamento),
departamento = gsub(pattern = "Choco", replacement = "Chocó", x = departamento),
departamento = gsub(pattern = "Cordoba", replacement = "Córdoba", x = departamento),
departamento = gsub(pattern = "Guainia", replacement = "Guainía", x = departamento),
departamento = gsub(pattern = "Narino", replacement = "Nariño", x = departamento),
departamento = gsub(pattern = "Quindio", replacement = "Quindío", x = departamento),
departamento = gsub(pattern = "San Andres Providencia y Sta C", replacement = "S.Andrés-Provid.-Sta.Cat.", x = departamento)) %>%
mutate(region = ifelse(departamento %in% c("Cauca", "Chocó", "Nariño", "Valle del Cauca"),
"Región Pacífico",
ifelse(departamento %in% c("Arauca", "Casanare", "Meta", "Vichada"),
"Región Orinoquía",
ifelse(departamento %in% c("Amazonas", "Caquetá", "Guainía", "Guaviare", "Putumayo"),
"Región Amazonas",
ifelse(departamento %in% c("Atlántico", "Bolívar",
"Cesar", "Córdoba", "La Guajira",
"Magdalena",
"S.Andrés-Provid.-Sta.Cat.",
"Sucre"), "Región Caribe", "Región Andina")))))
head(df_pretem)
dim(df_pretem)
[1] 5496 7
Finalmente después de la depuración y asegurar que la base de datos está como se desea, se guardará la base de datos en el directorio de trabajo en formato csv con el nombre precipitaciones_temperaturas.csv.
write_csv(x = df_pretem, file = "precipitaciones_temperaturas.csv")
Veamos la estructura de la base de datos que contruimos. Hagamos la lectura para realizar un resumen de los datos.
<- read_csv(file = "precipitaciones_temperaturas.csv") df_datos
df_datos
skim(df_datos)
── Data Summary ────────────────────────
Values
Name df_datos
Number of rows 5496
Number of columns 7
_______________________
Column type frequency:
character 4
numeric 3
________________________
Group variables None
── Variable type: character ─────────────────────────────────────────
skim_variable n_missing complete_rate min max empty n_unique
1 departamento 0 1 4 25 0 32
2 municipio 0 1 4 27 0 342
3 mes 0 1 4 10 0 12
4 region 0 1 13 16 0 5
whitespace
1 0
2 0
3 0
4 0
── Variable type: numeric ───────────────────────────────────────────
skim_variable n_missing complete_rate mean sd p0 p25
1 altitud 0 1 1068. 975. 1 152
2 precipitaciones 0 1 172. 136. 0.5 78.9
3 temperaturas 0 1 22.3 5.52 4.4 18.0
p50 p75 p100 hist
1 954. 1850 4150 ▇▃▃▂▁
2 136. 225 911. ▇▃▁▁▁
3 23.9 27 30.9 ▁▂▃▅▇
Editaremos los nombres de los meses, pondremos la primera letra del mes en mayúscula.. (Se harán los cambios pero no se guardarán en la base de datos, se harán para mostrar el uso de las funciones.)
Para poner la primera letra en mayúscula de una cadena de caracteres, se usa la función capitalize
del paquete Hmisc
.
library(Hmisc)
capitalize(df_datos$mes)
Obtengamos algunas estadísticas con los paquete base de R para la variable precipitaciones:
mean(df_datos$precipitaciones)
[1] 172.1682
median(df_datos$precipitaciones)
[1] 136.3
quantile(df_datos$precipitaciones)
0% 25% 50% 75% 100%
0.500 78.875 136.300 225.000 911.300
quantile(df_datos$precipitaciones, probs = seq(from = 0.1, to = 1, by = 0.1))
10% 20% 30% 40% 50% 60% 70% 80% 90%
42.45 66.10 89.40 111.20 136.30 165.80 202.50 256.50 347.80
100%
911.30
sd(df_datos$precipitaciones)
[1] 135.6864
sd(df_datos$precipitaciones)/mean(df_datos$precipitaciones)
[1] 0.7881037
# Paquete con función para hallar kurtosis de un conjunto de datos.
library(moments)
kurtosis(df_datos$precipitaciones)
[1] 6.844173
var(df_datos$precipitaciones)
[1] 18410.8
library(gridExtra)
<- df_datos %>%
g1 ggplot(mapping = aes(x = precipitaciones)) +
geom_histogram(aes(y = ..density..),
colour = 1, fill = "firebrick2") +
geom_density(lwd = 1, colour = 4,
fill = 4, alpha = 0.3)+
geom_vline(xintercept = quantile(df_datos$precipitaciones),
linetype='dashed')+
scale_x_continuous(n.breaks = 10)+
labs(title = "Densidad - Histograma de Precipitaciones",
x = "Precipitaciones (mm)",
y = "Densidad")+
theme_bw()
<- df_datos %>%
g2 ggplot(mapping = aes(x = precipitaciones))+
geom_boxplot(fill = "firebrick2", alpha = 0.8)+
labs(title = "Boxplot Precipitaciones",
x = "Precipitaciones (mm)", y = "")+
scale_x_continuous(n.breaks = 10)+
theme_bw()
<- df_datos %>%
g3 ggplot(mapping = aes(x = temperaturas)) +
geom_histogram(aes(y = ..density..),
colour = 1, fill = "purple") +
geom_density(lwd = 1, colour = "orange",
fill = "orange", alpha = 0.3)+
scale_x_continuous(n.breaks = 15)+
geom_vline(xintercept = quantile(df_datos$temperaturas),
linetype='dashed')+
labs(title = "Densidad - Histograma de Temperaturas",
x = "Temperaturas °C",
y = "Densidad")+
theme_bw()
<- df_datos %>%
g4 ggplot(mapping = aes(x = temperaturas))+
geom_boxplot(fill = "purple", alpha = 0.8)+
labs(title = "Boxplot Temperaturas",
x = "Temperaturas °C", y = "")+
scale_x_continuous(n.breaks = 15)+
theme_bw()
<- df_datos %>%
g5 ggplot(mapping = aes(x = altitud)) +
geom_histogram(aes(y = ..density..),
colour = 1, fill = "slategray") +
geom_density(lwd = 1, colour = 3,
fill = 4, alpha = 0.3)+
geom_vline(xintercept = quantile(df_datos$altitud),
linetype='dashed')+
scale_x_continuous(n.breaks = 10)+
labs(title = "Densidad - Histograma de Altitud",
x = "Altitud (m))",
y = "Densidad")+
theme_bw()
<- df_datos %>%
g6 ggplot(mapping = aes(x = altitud))+
geom_boxplot(fill = "slategray", alpha = 0.8)+
labs(title = "Boxplot Altitud",
x = "Altitud (m)", y = "")+
scale_x_continuous(n.breaks = 10)+
theme_bw()
grid.arrange(g1, g2, g3, g4, g5, g6, nrow=3)
Se obtendrá un resumen numérico de las variables en forma tabular para cada departamento. Se obtendrán el promedio, la mediana, el valor máximo, el valor mínimo, la desviación estándar, el coeficiente de variación, kurtosis y los quartiles 25, 50 y 75.
También es posible obtener el resumen para cada municipio, basta con agrupar los datos por municipio y obtener las estadísticas que se desee.
%>%
df_datos # agrupar por departamento
group_by(departamento) %>%
# obtener estadísticas
summarise(prom_pre = mean(precipitaciones),
med_pre = median(precipitaciones),
max_pre = max(precipitaciones),
min_pre = min(precipitaciones),
de_pre = sd(precipitaciones),
p25 = quantile(precipitaciones, probs = 0.25),
p50 = quantile(precipitaciones, probs = 0.5),
p75 = quantile(precipitaciones, probs = 0.75),
cv = round(sd(precipitaciones)/mean(precipitaciones), digits = 2),
Kurt = kurtosis(precipitaciones))
A través del diagrama de caja es posible resumir de manera gráfica algunas de las estadíticas obtenidas. Haciendo uso de la tubería %>%
es posible encadenar código para hacer operaciones sobre los datos y después graficar.
%>%
df_datos ggplot(mapping = aes(x = departamento, y = precipitaciones))+
geom_boxplot(fill = "slategray")+
labs(title = "Distribución Precipitaciones por Departamento",
x = "Departamento", y = "Precipitaciones (mm)")+
theme(legend.position = "none", axis.text.x = element_text(angle = 45))
%>%
df_datos group_by(departamento) %>%
summarise(prom_pre = mean(temperaturas),
med_pre = median(temperaturas),
max_pre = max(temperaturas),
min_pre = min(temperaturas),
de_pre = sd(temperaturas),
cv = round(sd(temperaturas)/mean(temperaturas), digits = 2),
kurt = kurtosis(temperaturas))
Para el gráfico de las temperaturas se hace uso de las facetas (facets), para dividir el gráfico en paneles que reperesentan cada departamento. Obtenedremos el diagrama de cajas y bigotes superpuesto con un gráfico de violín para conocer la distribución de la variable temperatura.
%>%
df_datos ggplot(mapping = aes(x = departamento, y = temperaturas), fill = departamento)+
geom_violin(fill = "steelblue", alpha = 0.6)+
geom_boxplot(alpha = 0.7)+
labs(title = "Distribución de Temperaturas por Departamento",
x = "", y = "Temperatura °C")+
facet_wrap(facets = ~departamento, scales = "free", nrow = 8)
%>%
df_datos mutate(mes = factor(x = mes, levels = c("enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"))) %>%
group_by(departamento, mes) %>%
summarise(prom = mean(precipitaciones)) %>%
ggplot(mapping = aes(y = prom, x = mes))+
geom_point(color = "blue")+
labs(title = "Promedio Precipitaciones por Mes y Departamento", x = "Mes", y = "Prom. Precipitaciones (mm)")+
facet_wrap(facets = ~departamento, nrow = 8)+
theme_bw()+
theme(legend.position = "none", axis.text.x = element_text(angle = 90))
library(gridExtra)
<- df_datos %>%
h1 group_by(departamento) %>%
summarise(tot_prep = round(mean(precipitaciones), digits = 2)) %>%
ggplot(mapping = aes(x = reorder(departamento, -tot_prep), y = tot_prep))+
geom_bar(stat = "identity", alpha = 0.9)+
scale_y_continuous(n.breaks = 6)+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Precipitaciones Promedio por Departamento", x = "", y = "Prom. Precipitaciones (mm)")
<- df_datos %>%
h2 group_by(departamento) %>%
summarise(tot_prep = round(mean(temperaturas), digits = 2)) %>%
ggplot(mapping = aes(x = reorder(departamento, -tot_prep), y = tot_prep))+
geom_bar(stat = "identity", alpha = 0.9)+
scale_y_continuous(n.breaks = 6)+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Temperaturas Promedio por Departamento", x = "", y = "Prom. Temperaturas (°C)")
<- df_datos %>%
h3 group_by(departamento) %>%
summarise(tot_prep = round(mean(altitud), digits = 2)) %>%
ggplot(mapping = aes(x = reorder(departamento, -tot_prep), y = tot_prep))+
geom_bar(stat = "identity", alpha = 0.9)+
scale_y_continuous(n.breaks = 6)+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Altitud Promedio por Departamento", x = "", y = "Prom. Altitud (m)")
grid.arrange(h1, h2, h3, nrow=2)
%>%
df_datos filter(departamento == c("Cundinamarca")) %>%
group_by(departamento, municipio) %>%
summarise(tot_prep = mean(altitud)) %>%
ungroup() %>%
ggplot(mapping = aes(x = municipio, y = tot_prep))+
geom_bar(fill = "darkolivegreen4",stat = "identity")+
geom_text(aes(label = tot_prep),
position = position_identity(),
vjust = -0.1,
color = "black",
size = 2.5)+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Precipitaciones Promedio Municipios de Cundinamarca", x = "", y = "Prom. Precipitaciones (mm)")+
facet_wrap(facets = ~departamento, scales = "free")
<- df_datos %>%
p1 group_by(region , departamento) %>%
summarise(tot_prep = mean(precipitaciones)) %>%
ungroup() %>%
ggplot(mapping = aes(x = departamento, y = tot_prep))+
geom_bar(fill = "darkslateblue",stat = "identity")+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Precipitaciones Promedio por Región", x = "", y = "Prom. Precipitaciones (mm)")+
facet_wrap(facets = ~region, scales = "free")
<- df_datos %>%
t1 ggplot(mapping = aes(x = departamento, y = temperaturas)) +
geom_boxplot(aes(fill = region))+
facet_wrap(facets = ~region, scales = "free")+
labs(title = "Temperatura por Región",
x = "Departamento", y = "Temperatura °C")+
theme(axis.text.x = element_text(angle = 90))+
theme(legend.position = "none")
grid.arrange(p1 , t1, nrow = 2)
%>%
df_datos filter(departamento == c("Meta", "Bolívar", "Chocó", "Santander",
"Nariño", "Arauca")) %>%
group_by(departamento, municipio) %>%
summarise(tot_prep = mean(precipitaciones)) %>%
ungroup() %>%
ggplot(mapping = aes(x = municipio, y = tot_prep))+
geom_bar(fill = "seagreen4",stat = "identity")+
theme_bw()+
theme(axis.text.x = element_text(angle = 90))+
labs(title = "Precipitaciones Promedio por Municipio y Departamento", x = "", y = "Prom. Precipitaciones (mm)")+
facet_wrap(facets = ~departamento, scales = "free")
Es posible obtener los valores de Covarianza para las variables. Para el caso de las variables altitud y temperaturas, se tiene que la realación que hay entre ellas es lineal y negativa.
cov(x = df_datos$altitud, y = df_datos$temperaturas)
[1] -5247.848
%>%
df_datos ggplot(mapping = aes(y = temperaturas, x = altitud))+
geom_point(aes(color = region))+
geom_smooth()+
scale_y_continuous(n.breaks = 8)+
labs(title = "Altitud vs Temperatura", x = "Altitud (m.s.n.m)", y = "Temperaturas (°C)")+
theme_bw()
%>%
df_datos group_by(departamento) %>%
summarise(prom_al = mean(altitud),
prom_tem = mean(temperaturas)) %>%
ggplot(mapping = aes(x = prom_al, y = prom_tem))+
geom_point(aes(color = departamento))+
geom_smooth()+
theme_bw()+
labs(title = "Promedio de Altitud-Temperatura",
subtitle = "Por Departamento",
x = "Altitud (m.s.n.m)",
y = "Temperatura °C",
caption = "Cada punto representa un Departamento")+
theme(legend.position = "none")
cov(x = df_datos$precipitaciones, y = df_datos$temperaturas)
[1] 143.5816
%>%
df_datos ggplot(mapping = aes(x = temperaturas, y = precipitaciones))+
geom_point(aes(color = region))+
geom_smooth()+
labs(title = "Temperaturas vs Precipitaciones", x = "Temperaturas °C", y = "Precipitaciones (mm)")+
theme_bw()
NA
%>%
df_datos group_by(departamento) %>%
summarise(prom_al = mean(precipitaciones),
prom_tem = mean(temperaturas)) %>%
ggplot(mapping = aes(y = prom_al, x = prom_tem))+
geom_point(aes(color = departamento))+
geom_smooth()+
theme_bw()+
labs(title = "Promedio Temperatura-Precipitaciones",
subtitle = "Por Departamento",
y = "Precipitaciones (mm)",
x = "Temperatura °C",
caption = "Cada punto representa un Departamento")+
theme(legend.position = "none")
%>%
df_datos ggplot(mapping = aes(y = precipitaciones, x = temperaturas))+
geom_point(color = "darkorange", alpha = 0.8)+
geom_smooth()+
labs(title = "Temparaturas y Precipitaciones",
subtitle = "Individual por Departamento",
x = "Temperaturas °C",
y = "Precipitaciones (mm)")+
theme_bw()+
facet_wrap(facets = ~departamento, scales = "free", nrow = 8)
%>%
df_datos ggplot(mapping = aes(y = precipitaciones, x = altitud))+
geom_smooth()+
labs(title = "Altitud y Precipitaciones",
subtitle = "Regiones Naturales",
x = "Altitud (m.s.n.m)",
y = "Precipitaciones (mm)")+
theme_bw()+
facet_wrap(facets = ~region, scales = "free", nrow = 2)
library(GGally)
ggpairs(df_datos, columns = c("precipitaciones", "temperaturas", "altitud"), ggplot2::aes(colour=region, alpha = 0.6))
ggcorr(df_datos, method = c("everything", "pearson"))