En la presente publicación se indican tres tipos de gráficos estadísticos a partir de tres bases de datos, con la finalidad de indicar una buena presentación de estos gráficos de manera que sean más entendibles y congruentes con la base de datos a la cual cada uno de estos representa, además presentando una breve descripción de los códigos ejecutados en Rstudio Las bases de datos utilizadas son:
Base Arveja: Donde presenta datos redondeados de una investigación de comportamiento en el rendimiento de algunos genotipos de arveja llevada a cabo en el municipio de Guaitarilla (Nariño). Para esta base de datos se utiliza un gráfico de barras.
Loblolly: Donde se presenta el seguimiento del crecimiento de árboles de pino denominados “Loblolly”, donde se estudia la edad, altura y semillas de estos árboles y la relación entre estas variables. Para esta base de datos utilicé un gráfico de histograma.
trees: Aquí se presentan datos de tres variables y su relación de plantas de cerezos negros, las variables evaluadas fueron: Circunferencia de troncos, Altura del árbol y volumen del mismo. Para esta base de datos utilizo un gráfico de puntos con linea de tendencia para revisar el comportamiento de la misma gráfica.
Orange: En esta base se presentan datos de la edad de árboles de naranja y su circunferencia, con el fin de realizar una comparación de éstos.Para esta base de datos utilicé un gráfico de líneas y en el cuál, en la parte final se muestra como un gráfico mas legible e interactivo.
A continuación activaré los distintos paquetes requeridos para la realizacion de graficos:
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.1.3
## Warning: package 'tibble' was built under R version 4.1.3
## Warning: package 'tidyr' was built under R version 4.1.3
## Warning: package 'readr' was built under R version 4.1.3
## Warning: package 'purrr' was built under R version 4.1.3
## Warning: package 'dplyr' was built under R version 4.1.3
## Warning: package 'stringr' was built under R version 4.1.3
## Warning: package 'forcats' was built under R version 4.1.3
## Warning: package 'lubridate' was built under R version 4.1.3
## -- Attaching core tidyverse packages ------------------------ tidyverse 2.0.0 --
## v dplyr 1.1.2 v readr 2.1.4
## v forcats 1.0.0 v stringr 1.5.0
## v ggplot2 3.4.4 v tibble 3.2.1
## v lubridate 1.9.2 v tidyr 1.3.0
## v purrr 1.0.1
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## i Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(plotly)
##
## Attaching package: 'plotly'
##
## The following object is masked from 'package:ggplot2':
##
## last_plot
##
## The following object is masked from 'package:stats':
##
## filter
##
## The following object is masked from 'package:graphics':
##
## layout
library(ggrepel)
## Warning: package 'ggrepel' was built under R version 4.1.3
library(PerformanceAnalytics)
## Warning: package 'PerformanceAnalytics' was built under R version 4.1.3
## Loading required package: xts
## Warning: package 'xts' was built under R version 4.1.3
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 4.1.3
##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'xts'
##
## The following objects are masked from 'package:dplyr':
##
## first, last
##
##
## Attaching package: 'PerformanceAnalytics'
##
## The following object is masked from 'package:graphics':
##
## legend
library(reshape2)
## Warning: package 'reshape2' was built under R version 4.1.3
##
## Attaching package: 'reshape2'
##
## The following object is masked from 'package:tidyr':
##
## smiths
library(readxl)
## Warning: package 'readxl' was built under R version 4.1.3
Voy a importar la base de datos “Base Arveja”
Base_arveja <- read_excel("C:/Users/PC/Desktop/Ing Agronomica/semestre 9/Software R/Taller 2/base de datos/Base arveja.xlsx")
View(Base_arveja)
Con los siguientes códigos voy a ver las principales caracteristicas de la base de datos:
head(Base_arveja)
## # A tibble: 6 x 2
## Genotipo Guaitarilla
## <chr> <dbl>
## 1 ARB 1 10
## 2 ARB 2 20
## 3 ARB 3 15
## 4 ARB 4 9
## 5 ARB 5 14
## 6 ARB 6 12
str(Base_arveja)
## tibble [20 x 2] (S3: tbl_df/tbl/data.frame)
## $ Genotipo : chr [1:20] "ARB 1" "ARB 2" "ARB 3" "ARB 4" ...
## $ Guaitarilla: num [1:20] 10 20 15 9 14 12 12 11 12 14 ...
tail(Base_arveja)
## # A tibble: 6 x 2
## Genotipo Guaitarilla
## <chr> <dbl>
## 1 ARB 15 17
## 2 ARB 16 12
## 3 ARB 17 11
## 4 ARB 18 14
## 5 ARB 19 14
## 6 ARB 20 8
names(Base_arveja)
## [1] "Genotipo" "Guaitarilla"
dim(Base_arveja)
## [1] 20 2
Con la siguiente función (attach(Base_arveja)) puedo visualizar los elementos de la base de datos solamente nombrandolos.
attach(Base_arveja)
Genotipo
## [1] "ARB 1" "ARB 2" "ARB 3" "ARB 4" "ARB 5" "ARB 6" "ARB 7" "ARB 8"
## [9] "ARB 9" "ARB 10" "ARB 11" "ARB 12" "ARB 13" "ARB 14" "ARB 15" "ARB 16"
## [17] "ARB 17" "ARB 18" "ARB 19" "ARB 20"
Guaitarilla
## [1] 10 20 15 9 14 12 12 11 12 14 13 13 13 13 17 12 11 14 14 8
detach(Base_arveja) Con esta la función deshago la función attach(Base_arveja)
detach(Base_arveja)
Con la función: ggplot(data = Base_arveja) + geom_bar(aes(x = Guaitarilla)) se realiza un gráfico de barras simple con los datos de la base de datos “Base_arveja”
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla))
A continuación, las funciones “factor” (cambiar valores para niveles) y “C” (que significa concatenar, se ordena los valores de x)
ggplot(data = Base_arveja) + geom_bar(aes(x = Guaitarilla))
unique(Base_arveja$Guaitarilla)
## [1] 10 20 15 9 14 12 11 13 17 8
Base_arveja$Guaitarilla <- factor(Base_arveja$Guaitarilla,
levels = c("10",
"20",
"15","9","14","12",
"11","13","17","8"))
Ejecutando la función “labs” permite organizar el gráfico con ítems como título, subtitulo, nombre de x, nombre de y, agregar comentarios.
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla)) +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos")
Con la función (fill = “” ) puedo dar colores al gráfico, existe una variedad de colores en el link: https://r-charts.com/es/paletas-colores/
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla), fill = "#8FD4B8") +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos")
Con la función (color = ““) se agregan bordes en el gráfico y con la función theme_dark() le doy un aspecto diferente al fondo, aunque esto tambien se puede cambiar según los temas disponibles en Rstudio.
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla),color = "#1E1E1E", fill = "#8FD4B8") +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos") + theme_dark()
Con la función geom_label se puede colocar un valor sobre las barras del gráfico.
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla),color = "#1E1E1E", fill = "#8FD4B8") +
geom_label(aes(x = Guaitarilla, label = ..count..), stat = "count") +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos")+ theme_dark()
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## i Please use `after_stat(count)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
con “vjust” se modifica la posición de las etiquetas según el número que se les asigne (en este caso, -3).
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla),color = "#1E1E1E", fill = "#8FD4B8") +
geom_text(aes(x = Guaitarilla, label = ..count..),
stat = "count", vjust = -3) +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos")+ theme_dark()
Ejecutando la función “coord_flip()” se pueden rotar las graficas.
ggplot(data = Base_arveja) +
geom_bar(aes(x = Guaitarilla),color = "#1E1E1E", fill = "#8FD4B8") +
geom_text(aes(x = Guaitarilla, label = ..count..), stat = "count", vjust = -3) +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos") + coord_flip()+ theme_dark()
Con la funcion fct_rev() se invierten las categorias.
ggplot(data = Base_arveja) +
geom_bar(aes(x = fct_rev(Guaitarilla)),color = "#1E1E1E", fill = "#8FD4B8") +
geom_text(aes(x = Guaitarilla, label = ..count..), stat = "count", vjust = 1) +
labs(title = "Genotipos de Arveja en Guaitarilla",
subtitle = "Rendimiento (Ton/ha)",
x = "Ton/ha",
y = "N° Genotipos",
caption = "Similitud de rendimientos en genotipos") + coord_flip()+ theme_dark()
A continuación voy a cargar la base de datos “Loblolly”
data("Loblolly")
Con la función “geom_histogram” se crea un gráfico de histogramas de la base de datos de “Loblolly”
ggplot(data = Loblolly) +
geom_histogram(aes(x = height))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Con las funciones: fill =““, theme_, color =”“, labs(); modificaré el color, el fondo del grafico de histograma,agregar unas caracteristicas al mismo y realizar los bordes al histograma.
ggplot(data = Loblolly) +
geom_histogram(aes(x = height), fill = "#FF3300")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
ggplot(data = Loblolly) +
geom_histogram(aes(x = height), fill = "#FF3300") +
theme_dark()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
ggplot(data = Loblolly) +
geom_histogram(aes(x = height), fill = "#FF3300", color = "black") +
labs(x = "Altura Árboles de Pino" ,
y = "Edad Árboles de Pino") +
theme_dark()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Con la función “bins=” se puede alterar la cantidad de cajas del histograma.
ggplot(data = Loblolly) +
geom_histogram(aes(x = height), fill = "#FF3300",
color = "black", bins = 84) +
labs(x = "Altura Árboles de Pino" ,
y = "Edad Árboles de Pino") +
theme_dark()
Cargaré la base de datos de “trees”
data("trees")
Con la función “geom_point()” se crea un grafico de puntos básico.
ggplot(trees) +
geom_point(aes(x = Height, y = Volume))
Con la función “size=” se hace que el tamaño de los puntos dependa de alguna de las variables, en este caso será “Grith”
ggplot(trees) +
geom_point(aes(x = Height, y = Volume, size = Girth))
Con la función “color= <” se va avisualizar una distincion de colores dependiendo a una categoría y al valor asignado, que para este caso la categoria será “Grith” y con valores menores a 13
ggplot(trees) +
geom_point(aes(x = Height, y = Volume,
size = Girth, color = Girth <13))
Utilizando la función “shape = >” puedo adicionar formas que dependan de la categoria y del valor asignado dentro de esta, donde para este caso seran la categoría “Height” con valores mayores a 73
ggplot(trees) +
geom_point(aes(x = Height, y = Volume,
size = Girth, color = Girth <13, shape= Height > 73)) +
labs(title = "Relación Entre Diametro, Altura y Volumen en Árboles de cereza negra",
x = "Height",
y = "Volume") +
theme_dark()
ggplot(trees) +
geom_point(aes(x = Height, y = Volume,
size = Girth, color = Girth <13, shape= Height > 73)) +
geom_smooth(aes(x = Height, y = Volume),
method = "loess", se = FALSE) +
labs(title = "Relación Entre Diametro, Altura y Volumen en Árboles de cereza negra",
x = "Height",
y = "Volume") +
theme_dark()
## `geom_smooth()` using formula = 'y ~ x'
Cargamos la base de datos “Orange”
data(Orange)
Con la función geom_point() + geom_smooth() se va a crear un gráfico de lineas simple.
ggplot(Orange) +
geom_point(aes(x = age, y = circumference)) +
geom_smooth(aes(x = age, y = circumference),
se = FALSE,
method = "loess")+
geom_text(aes(x = age, y = circumference, label = Tree))
## `geom_smooth()` using formula = 'y ~ x'
Con la guncion log() transformo las variables del eje Y.
ggplot(Orange) +
geom_point(aes(x = age, y = log(circumference))) +
geom_smooth(aes(x = age, y = log(circumference)),
se = F,
method = "loess")+
geom_text(aes(x = age, y = log (circumference), label = Tree))
## `geom_smooth()` using formula = 'y ~ x'
La función facet_wrap permite adicionar gráficos de acuerdo a otra variable de la base de datos.
ggplot(Orange) +
geom_point(aes(x = age, y = log(circumference))) +
geom_smooth(aes(x = age, y = log(circumference)),
se = F,
method = "loess")+
geom_text(aes(x = age, y = log (circumference), label = Tree)) +
facet_wrap(~Tree) +
theme_dark()
## `geom_smooth()` using formula = 'y ~ x'
Finalmente, al agregar la función ggplotly() permite que la gráfica se compote de forma interactiva.
ggplotly(ggplot(Orange) +
geom_point(aes(x = age, y = log(circumference))) +
geom_smooth(aes(x = age, y = log(circumference)),
se = F,
method = "loess")+
geom_text(aes(x = age, y = log (circumference), label = Tree)) +
facet_wrap(~Tree) +
theme_dark())
## `geom_smooth()` using formula = 'y ~ x'