Visualizacion de datos ggplot2

Para comenzar, lo primero que debemos hacer es instalar las librerías necesarias para la visualización y manipulación de datos. Es posible que ya las tengas instaladas.

INSTALAR Y CARGAR DATOS

install.packages("dplyr")    # Manipulación de datos
install.packages("tidyr")    # Manipulación de datos
install.packages("tidyverse")# Manipulación de datos
install.packages("reshape2") # Transformación de datos

install.packages("ggplot2")  # Visualización grafica
install.packages("cowplot")  # Generar varios graficos en una misma figura
install.packages("RColorBrewer")  # Generar varios graficos en una misma figura
install.packages("paletteer")  # Generar varios graficos en una misma figura
install.packages("ggthemes") # Temas de ggplot

Despues de instalarlos vamos a cargar los paquetes, para cargarlos nesecitamos la funcion library(nombre_paquete)

###---- Cargar paquetes ----
library(ggthemes) # Temas de ggplot
library(dplyr)     # Manipulación de datos
library(tidyr)     # Manipulación de datos
library(tidyverse) # Manipulación de datos
library(reshape2)  # Transformación de datos
library(pacman)
library(cowplot)   # Visualización grafica
library(ggplot2)   # Generar varios graficos en una misma figura
library(RColorBrewer) # Paletas de colores, Info en https://r-graph-gallery.com/38-rcolorbrewers-palettes.html
library(paletteer) # Paletas de colores, Info en https://pmassicotte.github.io/paletteer_gallery/

Hecho esto, lo primero que podemos hacer con el paquete RColorBrewer

DEFINIR ENTORNO

## Obtener gama de colores
display.brewer.all()

Este comando nos da algunas paletas de colores que ya nos dan los paquetes

Declaramos una variable llamada `indir que va a tener la direccion a la carpeta de la leccion de hoy.

###--- Directorio ----
# getwd() # nota de aqui saque la direccion
indir <- "/home/suaria/Documentos/VieRnesBioinformatica.github.io/content/es/posts/Viernes de Bioinformatica 2024/Viernes-8/RMDWN/a/"

Cargamos los archivos con la funcion read.csv en conjunto con paste0 para dar el directorio completo de los archivos.

Estos primeros 3 datasets son sobre personajes de Marvel y DC comics

###--- Data ----
infoCharacters <- read.csv(paste0(indir,"data/heroesInformation.csv"), na.strings = c("-", "-99")) # La opcion na.string nos permite sustituir valores - y -99 por NA
infoPowers <- read.csv(paste0(indir,"data/superHeroPowers.csv"))
infoStats <- read.csv(paste0(indir,"data/charactersStats.csv"), na.strings = "")

Este dataset contiene informacion de mamiferos

#Base de datos de los valores de Home ranch (rango de hogar) (log10) y valores de masa corporal (log10) para 462 especies de mamíferos
#Tucker, M. A. et al; Home range-body size patterns: are all mammals equal?
#https://onlinelibrary.wiley.com/journal/14668238?journalRedirectCheck=true
bd<- read.csv(paste0(indir,"data/MMHOME.csv"))


###--- Resumen de la informacion ----
summary(infoCharacters)
##        X             name              Gender           Eye.color        
##  Min.   :  0.0   Length:734         Length:734         Length:734        
##  1st Qu.:183.2   Class :character   Class :character   Class :character  
##  Median :366.5   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :366.5                                                           
##  3rd Qu.:549.8                                                           
##  Max.   :733.0                                                           
##                                                                          
##      Race            Hair.color            Height       Publisher        
##  Length:734         Length:734         Min.   :-99.0   Length:734        
##  Class :character   Class :character   1st Qu.:-99.0   Class :character  
##  Mode  :character   Mode  :character   Median :175.0   Mode  :character  
##                                        Mean   :102.3                     
##                                        3rd Qu.:185.0                     
##                                        Max.   :975.0                     
##                                                                          
##   Skin.color         Alignment             Weight      
##  Length:734         Length:734         Min.   :-99.00  
##  Class :character   Class :character   1st Qu.:-99.00  
##  Mode  :character   Mode  :character   Median : 62.00  
##                                        Mean   : 43.86  
##                                        3rd Qu.: 90.00  
##                                        Max.   :900.00  
##                                        NA's   :2
summary(infoPowers)
##   hero_names          Agility          Accelerated.Healing Lantern.Power.Ring
##  Length:667         Length:667         Length:667          Length:667        
##  Class :character   Class :character   Class :character    Class :character  
##  Mode  :character   Mode  :character   Mode  :character    Mode  :character  
##  Dimensional.Awareness Cold.Resistance     Durability          Stealth         
##  Length:667            Length:667         Length:667         Length:667        
##  Class :character      Class :character   Class :character   Class :character  
##  Mode  :character      Mode  :character   Mode  :character   Mode  :character  
##  Energy.Absorption     Flight          Danger.Sense       Underwater.breathing
##  Length:667         Length:667         Length:667         Length:667          
##  Class :character   Class :character   Class :character   Class :character    
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character    
##  Marksmanship       Weapons.Master     Power.Augmentation Animal.Attributes 
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Longevity         Intelligence       Super.Strength     Cryokinesis       
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Telepathy         Energy.Armor       Energy.Blasts      Duplication       
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Size.Changing      Density.Control      Stamina          Astral.Travel     
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Audio.Control       Dexterity           Omnitrix         Super.Speed       
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Possession        Animal.Oriented.Powers Weapon.based.Powers
##  Length:667         Length:667             Length:667         
##  Class :character   Class :character       Class :character   
##  Mode  :character   Mode  :character       Mode  :character   
##  Electrokinesis     Darkforce.Manipulation Death.Touch       
##  Length:667         Length:667             Length:667        
##  Class :character   Class :character       Class :character  
##  Mode  :character   Mode  :character       Mode  :character  
##  Teleportation      Enhanced.Senses    Telekinesis        Energy.Beams      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##     Magic           Hyperkinesis           Jump           Clairvoyance      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Dimensional.Travel Power.Sense        Shapeshifting      Peak.Human.Condition
##  Length:667         Length:667         Length:667         Length:667          
##  Class :character   Class :character   Class :character   Class :character    
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character    
##  Immortality         Camouflage        Element.Control      Phasing         
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Astral.Projection  Electrical.Transport Fire.Control        Projection       
##  Length:667         Length:667           Length:667         Length:667        
##  Class :character   Class :character     Class :character   Class :character  
##  Mode  :character   Mode  :character     Mode  :character   Mode  :character  
##   Summoning         Enhanced.Memory      Reflexes         Invulnerability   
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Energy.Constructs  Force.Fields       Self.Sustenance    Anti.Gravity      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##    Empathy          Power.Nullifier    Radiation.Control  Psionic.Powers    
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Elasticity        Substance.Secretion Elemental.Transmogrification
##  Length:667         Length:667          Length:667                  
##  Class :character   Class :character    Class :character            
##  Mode  :character   Mode  :character    Mode  :character            
##  Technopath.Cyberpath Photographic.Reflexes Seismic.Power     
##  Length:667           Length:667            Length:667        
##  Class :character     Class :character      Class :character  
##  Mode  :character     Mode  :character      Mode  :character  
##   Animation         Precognition       Mind.Control       Fire.Resistance   
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Power.Absorption   Enhanced.Hearing    Nova.Force          Insanity        
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Hypnokinesis       Animal.Control     Natural.Armor      Intangibility     
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Enhanced.Sight     Molecular.Manipulation Heat.Generation   
##  Length:667         Length:667             Length:667        
##  Class :character   Class :character       Class :character  
##  Mode  :character   Mode  :character       Mode  :character  
##   Adaptation          Gliding           Power.Suit         Mind.Blast       
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Probability.Manipulation Gravity.Control    Regeneration      
##  Length:667               Length:667         Length:667        
##  Class :character         Class :character   Class :character  
##  Mode  :character         Mode  :character   Mode  :character  
##  Light.Control      Echolocation        Levitation       
##  Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character  
##  Toxin.and.Disease.Control    Banish          Energy.Manipulation
##  Length:667                Length:667         Length:667         
##  Class :character          Class :character   Class :character   
##  Mode  :character          Mode  :character   Mode  :character   
##  Heat.Resistance    Natural.Weapons    Time.Travel        Enhanced.Smell    
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Illusions         Thirstokinesis     Hair.Manipulation  Illumination      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Omnipotent          Cloaking         Changing.Armor     Power.Cosmic      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Biokinesis        Water.Control      Radiation.Immunity Vision...Telescopic
##  Length:667         Length:667         Length:667         Length:667         
##  Class :character   Class :character   Class :character   Class :character   
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character   
##  Toxin.and.Disease.Resistance Spatial.Awareness  Energy.Resistance 
##  Length:667                   Length:667         Length:667        
##  Class :character             Class :character   Class :character  
##  Mode  :character             Mode  :character   Mode  :character  
##  Telepathy.Resistance Molecular.Combustion Omnilingualism    
##  Length:667           Length:667           Length:667        
##  Class :character     Class :character     Class :character  
##  Mode  :character     Mode  :character     Mode  :character  
##  Portal.Creation     Magnetism         Mind.Control.Resistance
##  Length:667         Length:667         Length:667             
##  Class :character   Class :character   Class :character       
##  Mode  :character   Mode  :character   Mode  :character       
##  Plant.Control         Sonar           Sonic.Scream       Time.Manipulation 
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Enhanced.Touch     Magic.Resistance   Invisibility       Sub.Mariner       
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Radiation.Absorption Intuitive.aptitude Vision...Microscopic
##  Length:667           Length:667         Length:667          
##  Class :character     Class :character   Class :character    
##  Mode  :character     Mode  :character   Mode  :character    
##    Melting          Wind.Control       Super.Breath       Wallcrawling      
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Vision...Night     Vision...Infrared  Grim.Reaping       Matter.Absorption 
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   The.Force         Resurrection       Terrakinesis       Vision...Heat     
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Vitakinesis        Radar.Sense        Qwardian.Power.Ring Weather.Control   
##  Length:667         Length:667         Length:667          Length:667        
##  Class :character   Class :character   Class :character    Class :character  
##  Mode  :character   Mode  :character   Mode  :character    Mode  :character  
##  Vision...X.Ray     Vision...Thermal   Web.Creation       Reality.Warping   
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##   Odin.Force        Symbiote.Costume   Speed.Force        Phoenix.Force     
##  Length:667         Length:667         Length:667         Length:667        
##  Class :character   Class :character   Class :character   Class :character  
##  Mode  :character   Mode  :character   Mode  :character   Mode  :character  
##  Molecular.Dissipation Vision...Cryo      Omnipresent         Omniscient       
##  Length:667            Length:667         Length:667         Length:667        
##  Class :character      Class :character   Class :character   Class :character  
##  Mode  :character      Mode  :character   Mode  :character   Mode  :character
summary(infoStats)
##      Name            Alignment          Intelligence      Strength     
##  Length:611         Length:611         Min.   :  1.0   Min.   :  1.00  
##  Class :character   Class :character   1st Qu.:  1.0   1st Qu.:  1.00  
##  Mode  :character   Mode  :character   Median : 50.0   Median : 10.00  
##                                        Mean   : 44.5   Mean   : 29.08  
##                                        3rd Qu.: 75.0   3rd Qu.: 53.00  
##                                        Max.   :113.0   Max.   :100.00  
##      Speed          Durability         Power            Combat      
##  Min.   :  1.00   Min.   :  1.00   Min.   :  0.00   Min.   :  1.00  
##  1st Qu.:  1.00   1st Qu.:  1.00   1st Qu.:  0.00   1st Qu.:  1.00  
##  Median : 23.00   Median : 32.00   Median : 37.00   Median : 50.00  
##  Mean   : 27.31   Mean   : 41.84   Mean   : 40.31   Mean   : 43.21  
##  3rd Qu.: 42.00   3rd Qu.: 80.00   3rd Qu.: 67.00   3rd Qu.: 70.00  
##  Max.   :100.00   Max.   :120.00   Max.   :100.00   Max.   :101.00  
##      Total      
##  Min.   :  5.0  
##  1st Qu.:  5.0  
##  Median :255.0  
##  Mean   :226.3  
##  3rd Qu.:351.5  
##  Max.   :581.0
summary(bd)
##        ID           Gender             Taxon             Home.range     
##  Min.   :  1.0   Length:462         Length:462         Min.   :-4.4400  
##  1st Qu.:116.2   Class :character   Class :character   1st Qu.:-2.1275  
##  Median :231.5   Mode  :character   Mode  :character   Median :-0.7100  
##  Mean   :231.5                                         Mean   :-0.5516  
##  3rd Qu.:346.8                                         3rd Qu.: 0.6550  
##  Max.   :462.0                                         Max.   : 5.6900  
##       Mass             Diet           Environment       
##  Min.   :-2.3800   Length:462         Length:462        
##  1st Qu.:-0.8300   Class :character   Class :character  
##  Median : 0.2400   Mode  :character   Mode  :character  
##  Mean   : 0.2419                                        
##  3rd Qu.: 1.1300                                        
##  Max.   : 4.5200

Informacion General sobre los personajes

###--- Data ----
head(infoCharacters)
##   X          name Gender Eye.color              Race Hair.color Height
## 1 0        A-Bomb   Male    yellow             Human    No Hair    203
## 2 1    Abe Sapien   Male      blue     Icthyo Sapien    No Hair    191
## 3 2      Abin Sur   Male      blue           Ungaran    No Hair    185
## 4 3   Abomination   Male     green Human / Radiation    No Hair    203
## 5 4       Abraxas   Male      blue     Cosmic Entity      Black    -99
## 6 5 Absorbing Man   Male      blue             Human    No Hair    193
##           Publisher Skin.color Alignment Weight
## 1     Marvel Comics       <NA>      good    441
## 2 Dark Horse Comics       blue      good     65
## 3         DC Comics        red      good     90
## 4     Marvel Comics       <NA>       bad    441
## 5     Marvel Comics       <NA>       bad    -99
## 6     Marvel Comics       <NA>       bad    122

Informacion sobre los poderes

head(infoPowers)
##    hero_names Agility Accelerated.Healing Lantern.Power.Ring
## 1     3-D Man    True               False              False
## 2      A-Bomb   False                True              False
## 3  Abe Sapien    True                True              False
## 4    Abin Sur   False               False               True
## 5 Abomination   False                True              False
## 6     Abraxas   False               False              False
##   Dimensional.Awareness Cold.Resistance Durability Stealth Energy.Absorption
## 1                 False           False      False   False             False
## 2                 False           False       True   False             False
## 3                 False            True       True   False             False
## 4                 False           False      False   False             False
## 5                 False           False      False   False             False
## 6                  True           False      False   False             False
##   Flight Danger.Sense Underwater.breathing Marksmanship Weapons.Master
## 1  False        False                False        False          False
## 2  False        False                False        False          False
## 3  False        False                 True         True           True
## 4  False        False                False        False          False
## 5  False        False                False        False          False
## 6   True        False                False        False          False
##   Power.Augmentation Animal.Attributes Longevity Intelligence Super.Strength
## 1              False             False     False        False           True
## 2              False             False      True        False           True
## 3              False             False      True         True           True
## 4              False             False     False        False          False
## 5              False             False     False         True           True
## 6              False             False     False         True           True
##   Cryokinesis Telepathy Energy.Armor Energy.Blasts Duplication Size.Changing
## 1       False     False        False         False       False         False
## 2       False     False        False         False       False         False
## 3       False      True        False         False       False         False
## 4       False     False        False         False       False         False
## 5       False     False        False         False       False         False
## 6       False     False        False         False       False          True
##   Density.Control Stamina Astral.Travel Audio.Control Dexterity Omnitrix
## 1           False    True         False         False     False    False
## 2           False    True         False         False     False    False
## 3           False    True         False         False     False    False
## 4           False   False         False         False     False    False
## 5           False    True         False         False     False    False
## 6           False   False         False         False     False    False
##   Super.Speed Possession Animal.Oriented.Powers Weapon.based.Powers
## 1        True      False                  False               False
## 2       False      False                  False               False
## 3       False      False                  False               False
## 4       False      False                  False               False
## 5        True      False                  False               False
## 6        True      False                  False               False
##   Electrokinesis Darkforce.Manipulation Death.Touch Teleportation
## 1          False                  False       False         False
## 2          False                  False       False         False
## 3          False                  False       False         False
## 4          False                  False       False         False
## 5          False                  False       False         False
## 6          False                  False       False          True
##   Enhanced.Senses Telekinesis Energy.Beams Magic Hyperkinesis  Jump
## 1           False       False        False False        False False
## 2           False       False        False False        False False
## 3           False       False        False False        False False
## 4           False       False        False False        False False
## 5           False       False        False False        False False
## 6           False       False        False  True        False False
##   Clairvoyance Dimensional.Travel Power.Sense Shapeshifting
## 1        False              False       False         False
## 2        False              False       False         False
## 3        False              False       False         False
## 4        False              False       False         False
## 5        False              False       False         False
## 6        False               True       False         False
##   Peak.Human.Condition Immortality Camouflage Element.Control Phasing
## 1                False       False      False           False   False
## 2                False       False       True           False   False
## 3                False        True      False           False   False
## 4                False       False      False           False   False
## 5                False       False      False           False   False
## 6                False        True      False           False   False
##   Astral.Projection Electrical.Transport Fire.Control Projection Summoning
## 1             False                False        False      False     False
## 2             False                False        False      False     False
## 3             False                False        False      False     False
## 4             False                False        False      False     False
## 5             False                False        False      False     False
## 6             False                False        False      False     False
##   Enhanced.Memory Reflexes Invulnerability Energy.Constructs Force.Fields
## 1           False    False           False             False        False
## 2           False    False           False             False        False
## 3           False     True           False             False        False
## 4           False    False           False             False        False
## 5           False    False            True             False        False
## 6           False    False            True             False        False
##   Self.Sustenance Anti.Gravity Empathy Power.Nullifier Radiation.Control
## 1           False        False   False           False             False
## 2            True        False   False           False             False
## 3           False        False   False           False             False
## 4           False        False   False           False             False
## 5           False        False   False           False             False
## 6           False        False   False           False             False
##   Psionic.Powers Elasticity Substance.Secretion Elemental.Transmogrification
## 1          False      False               False                        False
## 2          False      False               False                        False
## 3          False      False               False                        False
## 4          False      False               False                        False
## 5          False      False               False                        False
## 6          False      False               False                        False
##   Technopath.Cyberpath Photographic.Reflexes Seismic.Power Animation
## 1                False                 False         False     False
## 2                False                 False         False     False
## 3                False                 False         False     False
## 4                False                 False         False     False
## 5                False                 False         False      True
## 6                False                 False         False     False
##   Precognition Mind.Control Fire.Resistance Power.Absorption Enhanced.Hearing
## 1        False        False           False            False            False
## 2        False        False           False            False            False
## 3        False        False           False            False            False
## 4        False        False           False            False            False
## 5        False        False           False            False            False
## 6        False        False           False            False            False
##   Nova.Force Insanity Hypnokinesis Animal.Control Natural.Armor Intangibility
## 1      False    False        False          False         False         False
## 2      False    False        False          False         False         False
## 3      False    False        False          False         False         False
## 4      False    False        False          False         False         False
## 5      False    False        False          False         False         False
## 6      False    False        False          False         False         False
##   Enhanced.Sight Molecular.Manipulation Heat.Generation Adaptation Gliding
## 1          False                  False           False      False   False
## 2          False                  False           False      False   False
## 3           True                  False           False      False   False
## 4          False                  False           False      False   False
## 5          False                  False           False      False   False
## 6          False                   True           False      False   False
##   Power.Suit Mind.Blast Probability.Manipulation Gravity.Control Regeneration
## 1      False      False                    False           False        False
## 2      False      False                    False           False        False
## 3      False      False                    False           False        False
## 4      False      False                    False           False        False
## 5      False      False                    False           False        False
## 6      False      False                    False           False        False
##   Light.Control Echolocation Levitation Toxin.and.Disease.Control Banish
## 1         False        False      False                     False  False
## 2         False        False      False                     False  False
## 3         False        False      False                     False  False
## 4         False        False      False                     False  False
## 5         False        False      False                     False  False
## 6         False        False      False                     False  False
##   Energy.Manipulation Heat.Resistance Natural.Weapons Time.Travel
## 1               False           False           False       False
## 2               False           False           False       False
## 3               False           False           False       False
## 4               False           False           False       False
## 5               False           False           False       False
## 6                True           False           False       False
##   Enhanced.Smell Illusions Thirstokinesis Hair.Manipulation Illumination
## 1          False     False          False             False        False
## 2          False     False          False             False        False
## 3          False     False          False             False        False
## 4          False     False          False             False        False
## 5          False     False          False             False        False
## 6          False     False          False             False        False
##   Omnipotent Cloaking Changing.Armor Power.Cosmic Biokinesis Water.Control
## 1      False    False          False        False      False         False
## 2      False    False          False        False      False         False
## 3      False    False          False        False      False         False
## 4      False    False          False        False      False         False
## 5      False    False          False        False      False         False
## 6      False    False          False         True      False         False
##   Radiation.Immunity Vision...Telescopic Toxin.and.Disease.Resistance
## 1              False               False                        False
## 2              False               False                        False
## 3              False               False                        False
## 4              False               False                        False
## 5              False               False                        False
## 6              False               False                        False
##   Spatial.Awareness Energy.Resistance Telepathy.Resistance Molecular.Combustion
## 1             False             False                False                False
## 2             False             False                False                False
## 3             False             False                False                False
## 4             False             False                False                False
## 5             False             False                False                False
## 6             False             False                False                False
##   Omnilingualism Portal.Creation Magnetism Mind.Control.Resistance
## 1          False           False     False                   False
## 2          False           False     False                   False
## 3          False           False     False                   False
## 4          False           False     False                   False
## 5          False           False     False                   False
## 6          False           False     False                   False
##   Plant.Control Sonar Sonic.Scream Time.Manipulation Enhanced.Touch
## 1         False False        False             False          False
## 2         False False        False             False          False
## 3         False False        False             False          False
## 4         False False        False             False          False
## 5         False False        False             False          False
## 6         False False        False             False          False
##   Magic.Resistance Invisibility Sub.Mariner Radiation.Absorption
## 1            False        False       False                False
## 2            False        False       False                False
## 3            False        False        True                False
## 4            False        False       False                False
## 5            False        False       False                False
## 6            False        False       False                False
##   Intuitive.aptitude Vision...Microscopic Melting Wind.Control Super.Breath
## 1              False                False   False        False        False
## 2              False                False   False        False        False
## 3              False                False   False        False        False
## 4              False                False   False        False        False
## 5              False                False   False        False         True
## 6              False                False   False        False        False
##   Wallcrawling Vision...Night Vision...Infrared Grim.Reaping Matter.Absorption
## 1        False          False             False        False             False
## 2        False          False             False        False             False
## 3        False          False             False        False             False
## 4        False          False             False        False             False
## 5        False          False             False        False             False
## 6        False          False             False        False             False
##   The.Force Resurrection Terrakinesis Vision...Heat Vitakinesis Radar.Sense
## 1     False        False        False         False       False       False
## 2     False        False        False         False       False       False
## 3     False        False        False         False       False       False
## 4     False        False        False         False       False       False
## 5     False        False        False         False       False       False
## 6     False        False        False         False       False       False
##   Qwardian.Power.Ring Weather.Control Vision...X.Ray Vision...Thermal
## 1               False           False          False            False
## 2               False           False          False            False
## 3               False           False          False            False
## 4               False           False          False            False
## 5               False           False          False            False
## 6               False           False          False            False
##   Web.Creation Reality.Warping Odin.Force Symbiote.Costume Speed.Force
## 1        False           False      False            False       False
## 2        False           False      False            False       False
## 3        False           False      False            False       False
## 4        False           False      False            False       False
## 5        False           False      False            False       False
## 6        False           False      False            False       False
##   Phoenix.Force Molecular.Dissipation Vision...Cryo Omnipresent Omniscient
## 1         False                 False         False       False      False
## 2         False                 False         False       False      False
## 3         False                 False         False       False      False
## 4         False                 False         False       False      False
## 5         False                 False         False       False      False
## 6         False                 False         False       False      False

Caracteristicas particulares como inteligencia, fuerza y velocidad.

head(infoStats)
##          Name Alignment Intelligence Strength Speed Durability Power Combat
## 1     3-D Man      good           50       31    43         32    25     52
## 2      A-Bomb      good           38      100    17         80    17     64
## 3  Abe Sapien      good           88       14    35         42    35     85
## 4    Abin Sur      good           50       90    53         64    84     65
## 5 Abomination       bad           63       80    53         90    55     95
## 6     Abraxas       bad           88      100    83         99   100     56
##   Total
## 1   233
## 2   316
## 3   299
## 4   406
## 5   436
## 6   526

PROCESAMIENTO DE DATOS

Vamos a hacer un poco de procesamiento con los datos para poder hacer las figuras.

###--- PROCESAMIENTO DE DATOS----
colnames(infoCharacters)[colnames(infoCharacters) == "name"] <- "Name"
colnames(infoPowers)[colnames(infoPowers) == "hero_names"] <- "Name"
unique(infoCharacters$Publisher)
##  [1] "Marvel Comics"     "Dark Horse Comics" "DC Comics"        
##  [4] "NBC - Heroes"      "Wildstorm"         "Image Comics"     
##  [7] ""                  "Icon Comics"       "SyFy"             
## [10] "Hanna-Barbera"     "George Lucas"      "Team Epic TV"     
## [13] "South Park"        "HarperCollins"     "ABC Studios"      
## [16] "Universal Studios" "Star Trek"         "IDW Publishing"   
## [19] "Shueisha"          "Sony Pictures"     "J. K. Rowling"    
## [22] "Titan Books"       "Rebellion"         "Microsoft"        
## [25] "J. R. R. Tolkien"
marvelDcInfo <- infoCharacters[(infoCharacters$Publisher == "Marvel Comics" | infoCharacters$Publisher == "DC Comics"), ]

marvelDcInfo <- marvelDcInfo[!duplicated(marvelDcInfo$Name), ]

marvelDcInfo <- marvelDcInfo %>%
  select(Name, Gender, Race, Publisher)

marvelDcStatsInfo <- left_join(marvelDcInfo, infoStats, by = "Name")
head(marvelDcStatsInfo)[1:5]
##            Name Gender              Race     Publisher Alignment
## 1        A-Bomb   Male             Human Marvel Comics      good
## 2      Abin Sur   Male           Ungaran     DC Comics      good
## 3   Abomination   Male Human / Radiation Marvel Comics       bad
## 4       Abraxas   Male     Cosmic Entity Marvel Comics       bad
## 5 Absorbing Man   Male             Human Marvel Comics      <NA>
## 6  Adam Strange   Male             Human     DC Comics      good
fullMarvelDc <- left_join(marvelDcStatsInfo, infoPowers, by = "Name")
head(fullMarvelDc)[1:5]
##            Name Gender              Race     Publisher Alignment
## 1        A-Bomb   Male             Human Marvel Comics      good
## 2      Abin Sur   Male           Ungaran     DC Comics      good
## 3   Abomination   Male Human / Radiation Marvel Comics       bad
## 4       Abraxas   Male     Cosmic Entity Marvel Comics       bad
## 5 Absorbing Man   Male             Human Marvel Comics      <NA>
## 6  Adam Strange   Male             Human     DC Comics      good
fullMarvelDc$Name <- as.factor(fullMarvelDc$Name)
fullMarvelDc$Gender <- as.factor(fullMarvelDc$Gender)
fullMarvelDc$Race <- as.factor(fullMarvelDc$Race)
fullMarvelDc$Publisher <- as.factor(fullMarvelDc$Publisher)
fullMarvelDc$Alignment <- as.factor(fullMarvelDc$Alignment)

marvelDcGender <- fullMarvelDc %>% filter(!is.na(Gender)) %>%
  group_by(Gender)%>%
  dplyr::count(Publisher) %>%
  select(Gender, Publisher, Count = n)

GRAFICAS BASICAS

BASE DEL GRAFICO

Vamos a empezar con las graficas basicas de ggplot

###--- Graficas basicas ----

# 1. Base del grafico
# ggplot con dos elementos basicos: 
#    - 1) la base de datos y 
#    - 2) los elementos esteticos. 
# ggplot de forma predeterminada muestra las coordenadas y el tema.

El primer argumento que le debes de dar primero es data, luego mapeamos los elementos visuales a las columnas

ggplot(data = marvelDcGender, mapping = aes(x = Gender, y = Count))

Establecimos a x como Gender y a y como Count, pero podras notar que no hay ninguna figura en el plot, el siguiente paso es agregar la geometria de puntos.

GEOMETRIA DE PUNTOS

#2. Se agregan las geometrias
# aes(), en este caso las variables (x, y) 
# Tipo de grafica = que queremos representar y agregamos el tipo de geometria para representar los datos.
# aplicar a todo el grafico y a las capas siguientes el mapping (overide posible)
ggplot(data = marvelDcGender) +
    geom_point(mapping = aes(x = Gender, y = Count)) # Grafica de puntos

# aplicar el mapping especifico a una capa (mas usado)
ggplot(data = marvelDcGender, mapping = aes(x = Gender, y = Count)) +
  geom_point()

ENRIQUECER EL GRAFICO

Algo que puede ser muy importante para los graficos es cambiar los colores.

Lo que haremos sera que el color dependa de la variable publisher.

#3. El grafico anterior se puede ir enriqueciendo al agregar atributos esteticos al mapping 
# o asignando atributos fuera del mapping. Recordar la diferencia entre el mapping y "setting aesthetics".

#a. Agregar elementos aeshetics al mapping

ggplot(marvelDcGender) + # Hacer que el color dependa de la variable Publisher
  geom_point(mapping = aes(x = Gender, y = Count, colour= Publisher)) 

Si nosotros queremos que un setting sea el color que nosotros queramos solo necesitamos añadir coulor = "color"

#b. Agregar elementos como setting aesthetics
ggplot(marvelDcGender) + 
    geom_point (aes(x = Gender, y = Count), colour="red")

ggplot(marvelDcGender) + 
  geom_point (aes(x = Gender, y = Count), colour="purple")

ggplot(marvelDcGender) + 
  geom_point (aes(x = Gender, y = Count), colour="blue")

TIPOS DE GEOMETRIAS

Ahora utilizaremos el data de infoCharacters, y que visualmente el eje de X sea la altura

###--- Tipos de geometrias ----

# PALETAS DE COLOR PERSONALIZADAS
dcMarvelPalette <- c("#0476F2", "#EC1E24")
goodBadPalette <- c("#A71D20", "#0DA751", "#818385")


# Para agregar geometrias que representen los datos hay que  utilizar la funcion  geom_ 
# que se usa en ggplot para representa un grafico por medio de objetos geometricos. 
# Y se compone de la palabra geom y luego el nombre de la geometr?a (en ingles).

# ONE VARIABLE continuous (valores)
c <- ggplot(infoCharacters, aes(x = Height))
c

El resultado se ve asi porque no se ha definidon la geometria y solo esta involucrado el eje X.

Agregamos diferentes geometrias para probar (Todas las opciones tienen su documentacion).

c + geom_area(stat = "bin")

c + geom_density(kernel = "gaussian")

c + geom_dotplot()

c + geom_freqpoly()

c + geom_histogram()

En este caso las opciones le otorgaron al eje y la cantidad de personajes que tienen esa altura.

# ONE VARIABLE discrete (cualidades)
d <- ggplot(infoCharacters, aes(x = Gender))
d

d + geom_bar()

#TWO VARIABLES both continuous 
e <- ggplot(data = infoCharacters, aes(x = Height, y = Weight))
e

e + geom_point()

e + geom_point(alpha=0.5)

# alpha es para poner transparencia y permite ver entre mas solido
# mas datos presentes

e + geom_line()

e + geom_count()

e + geom_step()

e + geom_smooth(method = lm) + # metodo lineal, regresion lineal
coord_flip() # para voltear x y y

#Etiquetas 
e + geom_label(aes(label= Publisher))

e + geom_text(aes(label= Publisher)) # remplazar puntos por letras

#one discrete, one continuous
f <- ggplot(marvelDcGender, aes(x = Gender, y = Count))
f

f + geom_col()

f + geom_boxplot()

f + geom_violin()

rm(f, e, d, c) #eliminar variables especificas

#both discrete
g <- ggplot(infoCharacters, aes(x = Gender, y = Publisher))
g

g + geom_count()

g + geom_jitter()

#Tres variables
g <- ggplot(infoCharacters, aes(x= Gender, y = Race))
g

g + geom_raster(aes(fill = Publisher))

#Aplica la grafica las capas con diferentes geoms
ggplot(bd, aes(x=Diet, y = Mass))+ 
    geom_boxplot() +
    geom_jitter() # +

  # geom_violin()

# Cuidado en el acomodo de las capas, la posicion de las mismas es importante
ggplot(bd, aes(x=Diet, y = Mass))+ 
  geom_jitter() +
  geom_boxplot()

# puedes seguir agregando capas, cada grafico es una capa
ggplot(bd, aes(x=Diet, y = Mass)) + 
  geom_boxplot() +
  geom_jitter() +
  geom_violin()

#Asignar varias capas y modificar los valores del mapping de la grafica. 
ggplot(bd, aes(x=Home.range, y = Mass))+ 
    geom_jitter(aes(colour=Diet, shape=Diet), size= 2.0, alpha = 0.8)+
    geom_smooth(method = lm, color="black") + # ajustar una linea
    scale_shape_manual(values=c(17, 18, 19)) +
    scale_color_manual(values=c('#CC0033','#E69F00', '#00CCCC'))

  # scale_color_manual(values=c("Carnivore" = '#CC0033', "Omnivore" = '#E69F00', "Herbivore" = '#00CCCC'))

########Etiquetado######################
#Asignar nombres al título, subtitulo, ejes
aa <- ggplot(bd, aes(x=Diet, y = Mass, fill=Diet)) + 
    geom_boxplot() +
    geom_jitter(colour="gray") +
    labs(title = "Rango de hogar y masa corporal", 
         subtitle = "Mamíferos",
         x = "Dieta", y = "Masa (log10)", 
         caption = "Datos: Tucker,(2014), Global Ecol. Biogeogr. 23, 1105–1114",
         fill = "Tipo de dieta")
aa

#########Themes#######
#Los temas son una forma de personalizar los componentes que no son datos de sus gráficos: títulos, etiquetas, fuentes, fondo, cuadrículas y leyendas. Los temas pueden ser utilizados para dar al grafico un aspecto personalizado. 
## Para ver los temas: https://ggplot2.tidyverse.org/reference/ggtheme.html

######Themas completos#############
aa + theme_gray()

aa + theme_light()

aa + theme_dark()

aa + theme_minimal()

aa + theme_void()

aa + theme_test()

aa + theme_classic()

#Manipular theme
?theme

#Asignar estilo a las letras titulo y ejes
#
aa +
    theme(plot.title = element_text(color="red", size=12, face="bold.italic"),
          axis.title.x = element_text(color="blue", size=12, face="bold"),
          axis.title.y = element_text(color="#993333", size=12, face="italic"),
          axis.text = element_text(colour = "#74008D"))

#Asignar estilo al panel
aa +
    theme(plot.background = element_rect(fill = "lightblue3", colour = "NA"),
          panel.background = element_rect(fill = "lightblue", colour = "red"))

#Si quiero usar un tipo de theme y asignar estilo a los títulos 
aa + theme_dark() +
    theme(plot.title = element_text(color="red", size=12, face="bold.italic"),
          axis.title.x = element_text(color="blue", size=12, face="bold"),
          axis.title.y = element_text(color="#993333", size=12, face="italic")
    )

####Escalas scale_()#####
#Una propiedad importante de ggplot2 es el principio de que cada estetica aes()está asociada a una escala.

#La función de ggplot predetermina los valores de las escalas dependiendo de tus datos
ggplot(bd, aes(x=Home.range , y = Mass))+
    geom_point(aes(colour = Diet))

#Dicho de explícitamente quedaría así
ggplot(bd, aes(x=Home.range , y = Mass))+
    geom_point(aes(colour = Diet))+
    scale_x_continuous() +
    scale_y_continuous() +
    scale_colour_discrete()

#Sintaxis para scale()
#1. scale
#2. El nombre de la estética principal(x,y, colour, shape, fill)
#3. El tipo de escala (continuous, discrete, brewer).

#USO GENERAL en la estética del gráfico
#scale_*_continuous() - Asignar valores continuos a valores visuales. 
#scale_*_discrete() - Asigna valores discretos a valores visuales. 
#scale_*_binned() - Asigna valores continuos a contenedores discretos. 
#scale_*_identity() - Usa valores de datos como valores visuales.
#scale_*_manual(values = c()) - Asigna valores discretos a valores visuales elegidos manualmente.

#Cambiemos algunos valores
ggplot(bd, aes(x=Home.range , y = Mass))+
    geom_point(aes(colour = Diet))+
    scale_x_continuous(name = "Rango de hogar (log)") +
    scale_y_continuous(name = "Masa (log)")+
    scale_colour_discrete(name="Dieta")

ggplot(bd, aes(x=Home.range , y = Mass))+
  geom_point(aes(colour = Diet))+
  scale_x_binned(name = "Rango de hogar (log)") +
  scale_y_continuous(name = "Masa (log)")+
  scale_colour_discrete(name="Dieta")

ggplot(bd, aes(x=Home.range , y = Mass))+
  geom_point(aes(colour = Diet))+
  scale_x_binned(name = "Rango de hogar (log)") +
  scale_y_binned(name = "Masa (log)")+
  scale_colour_discrete(name="Dieta")

###Colores####
#Colores predeterminados
#http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf
head(colors(), n = 20)
##  [1] "white"         "aliceblue"     "antiquewhite"  "antiquewhite1"
##  [5] "antiquewhite2" "antiquewhite3" "antiquewhite4" "aquamarine"   
##  [9] "aquamarine1"   "aquamarine2"   "aquamarine3"   "aquamarine4"  
## [13] "azure"         "azure1"        "azure2"        "azure3"       
## [17] "azure4"        "beige"         "bisque"        "bisque1"
colors()
##   [1] "white"                "aliceblue"            "antiquewhite"        
##   [4] "antiquewhite1"        "antiquewhite2"        "antiquewhite3"       
##   [7] "antiquewhite4"        "aquamarine"           "aquamarine1"         
##  [10] "aquamarine2"          "aquamarine3"          "aquamarine4"         
##  [13] "azure"                "azure1"               "azure2"              
##  [16] "azure3"               "azure4"               "beige"               
##  [19] "bisque"               "bisque1"              "bisque2"             
##  [22] "bisque3"              "bisque4"              "black"               
##  [25] "blanchedalmond"       "blue"                 "blue1"               
##  [28] "blue2"                "blue3"                "blue4"               
##  [31] "blueviolet"           "brown"                "brown1"              
##  [34] "brown2"               "brown3"               "brown4"              
##  [37] "burlywood"            "burlywood1"           "burlywood2"          
##  [40] "burlywood3"           "burlywood4"           "cadetblue"           
##  [43] "cadetblue1"           "cadetblue2"           "cadetblue3"          
##  [46] "cadetblue4"           "chartreuse"           "chartreuse1"         
##  [49] "chartreuse2"          "chartreuse3"          "chartreuse4"         
##  [52] "chocolate"            "chocolate1"           "chocolate2"          
##  [55] "chocolate3"           "chocolate4"           "coral"               
##  [58] "coral1"               "coral2"               "coral3"              
##  [61] "coral4"               "cornflowerblue"       "cornsilk"            
##  [64] "cornsilk1"            "cornsilk2"            "cornsilk3"           
##  [67] "cornsilk4"            "cyan"                 "cyan1"               
##  [70] "cyan2"                "cyan3"                "cyan4"               
##  [73] "darkblue"             "darkcyan"             "darkgoldenrod"       
##  [76] "darkgoldenrod1"       "darkgoldenrod2"       "darkgoldenrod3"      
##  [79] "darkgoldenrod4"       "darkgray"             "darkgreen"           
##  [82] "darkgrey"             "darkkhaki"            "darkmagenta"         
##  [85] "darkolivegreen"       "darkolivegreen1"      "darkolivegreen2"     
##  [88] "darkolivegreen3"      "darkolivegreen4"      "darkorange"          
##  [91] "darkorange1"          "darkorange2"          "darkorange3"         
##  [94] "darkorange4"          "darkorchid"           "darkorchid1"         
##  [97] "darkorchid2"          "darkorchid3"          "darkorchid4"         
## [100] "darkred"              "darksalmon"           "darkseagreen"        
## [103] "darkseagreen1"        "darkseagreen2"        "darkseagreen3"       
## [106] "darkseagreen4"        "darkslateblue"        "darkslategray"       
## [109] "darkslategray1"       "darkslategray2"       "darkslategray3"      
## [112] "darkslategray4"       "darkslategrey"        "darkturquoise"       
## [115] "darkviolet"           "deeppink"             "deeppink1"           
## [118] "deeppink2"            "deeppink3"            "deeppink4"           
## [121] "deepskyblue"          "deepskyblue1"         "deepskyblue2"        
## [124] "deepskyblue3"         "deepskyblue4"         "dimgray"             
## [127] "dimgrey"              "dodgerblue"           "dodgerblue1"         
## [130] "dodgerblue2"          "dodgerblue3"          "dodgerblue4"         
## [133] "firebrick"            "firebrick1"           "firebrick2"          
## [136] "firebrick3"           "firebrick4"           "floralwhite"         
## [139] "forestgreen"          "gainsboro"            "ghostwhite"          
## [142] "gold"                 "gold1"                "gold2"               
## [145] "gold3"                "gold4"                "goldenrod"           
## [148] "goldenrod1"           "goldenrod2"           "goldenrod3"          
## [151] "goldenrod4"           "gray"                 "gray0"               
## [154] "gray1"                "gray2"                "gray3"               
## [157] "gray4"                "gray5"                "gray6"               
## [160] "gray7"                "gray8"                "gray9"               
## [163] "gray10"               "gray11"               "gray12"              
## [166] "gray13"               "gray14"               "gray15"              
## [169] "gray16"               "gray17"               "gray18"              
## [172] "gray19"               "gray20"               "gray21"              
## [175] "gray22"               "gray23"               "gray24"              
## [178] "gray25"               "gray26"               "gray27"              
## [181] "gray28"               "gray29"               "gray30"              
## [184] "gray31"               "gray32"               "gray33"              
## [187] "gray34"               "gray35"               "gray36"              
## [190] "gray37"               "gray38"               "gray39"              
## [193] "gray40"               "gray41"               "gray42"              
## [196] "gray43"               "gray44"               "gray45"              
## [199] "gray46"               "gray47"               "gray48"              
## [202] "gray49"               "gray50"               "gray51"              
## [205] "gray52"               "gray53"               "gray54"              
## [208] "gray55"               "gray56"               "gray57"              
## [211] "gray58"               "gray59"               "gray60"              
## [214] "gray61"               "gray62"               "gray63"              
## [217] "gray64"               "gray65"               "gray66"              
## [220] "gray67"               "gray68"               "gray69"              
## [223] "gray70"               "gray71"               "gray72"              
## [226] "gray73"               "gray74"               "gray75"              
## [229] "gray76"               "gray77"               "gray78"              
## [232] "gray79"               "gray80"               "gray81"              
## [235] "gray82"               "gray83"               "gray84"              
## [238] "gray85"               "gray86"               "gray87"              
## [241] "gray88"               "gray89"               "gray90"              
## [244] "gray91"               "gray92"               "gray93"              
## [247] "gray94"               "gray95"               "gray96"              
## [250] "gray97"               "gray98"               "gray99"              
## [253] "gray100"              "green"                "green1"              
## [256] "green2"               "green3"               "green4"              
## [259] "greenyellow"          "grey"                 "grey0"               
## [262] "grey1"                "grey2"                "grey3"               
## [265] "grey4"                "grey5"                "grey6"               
## [268] "grey7"                "grey8"                "grey9"               
## [271] "grey10"               "grey11"               "grey12"              
## [274] "grey13"               "grey14"               "grey15"              
## [277] "grey16"               "grey17"               "grey18"              
## [280] "grey19"               "grey20"               "grey21"              
## [283] "grey22"               "grey23"               "grey24"              
## [286] "grey25"               "grey26"               "grey27"              
## [289] "grey28"               "grey29"               "grey30"              
## [292] "grey31"               "grey32"               "grey33"              
## [295] "grey34"               "grey35"               "grey36"              
## [298] "grey37"               "grey38"               "grey39"              
## [301] "grey40"               "grey41"               "grey42"              
## [304] "grey43"               "grey44"               "grey45"              
## [307] "grey46"               "grey47"               "grey48"              
## [310] "grey49"               "grey50"               "grey51"              
## [313] "grey52"               "grey53"               "grey54"              
## [316] "grey55"               "grey56"               "grey57"              
## [319] "grey58"               "grey59"               "grey60"              
## [322] "grey61"               "grey62"               "grey63"              
## [325] "grey64"               "grey65"               "grey66"              
## [328] "grey67"               "grey68"               "grey69"              
## [331] "grey70"               "grey71"               "grey72"              
## [334] "grey73"               "grey74"               "grey75"              
## [337] "grey76"               "grey77"               "grey78"              
## [340] "grey79"               "grey80"               "grey81"              
## [343] "grey82"               "grey83"               "grey84"              
## [346] "grey85"               "grey86"               "grey87"              
## [349] "grey88"               "grey89"               "grey90"              
## [352] "grey91"               "grey92"               "grey93"              
## [355] "grey94"               "grey95"               "grey96"              
## [358] "grey97"               "grey98"               "grey99"              
## [361] "grey100"              "honeydew"             "honeydew1"           
## [364] "honeydew2"            "honeydew3"            "honeydew4"           
## [367] "hotpink"              "hotpink1"             "hotpink2"            
## [370] "hotpink3"             "hotpink4"             "indianred"           
## [373] "indianred1"           "indianred2"           "indianred3"          
## [376] "indianred4"           "ivory"                "ivory1"              
## [379] "ivory2"               "ivory3"               "ivory4"              
## [382] "khaki"                "khaki1"               "khaki2"              
## [385] "khaki3"               "khaki4"               "lavender"            
## [388] "lavenderblush"        "lavenderblush1"       "lavenderblush2"      
## [391] "lavenderblush3"       "lavenderblush4"       "lawngreen"           
## [394] "lemonchiffon"         "lemonchiffon1"        "lemonchiffon2"       
## [397] "lemonchiffon3"        "lemonchiffon4"        "lightblue"           
## [400] "lightblue1"           "lightblue2"           "lightblue3"          
## [403] "lightblue4"           "lightcoral"           "lightcyan"           
## [406] "lightcyan1"           "lightcyan2"           "lightcyan3"          
## [409] "lightcyan4"           "lightgoldenrod"       "lightgoldenrod1"     
## [412] "lightgoldenrod2"      "lightgoldenrod3"      "lightgoldenrod4"     
## [415] "lightgoldenrodyellow" "lightgray"            "lightgreen"          
## [418] "lightgrey"            "lightpink"            "lightpink1"          
## [421] "lightpink2"           "lightpink3"           "lightpink4"          
## [424] "lightsalmon"          "lightsalmon1"         "lightsalmon2"        
## [427] "lightsalmon3"         "lightsalmon4"         "lightseagreen"       
## [430] "lightskyblue"         "lightskyblue1"        "lightskyblue2"       
## [433] "lightskyblue3"        "lightskyblue4"        "lightslateblue"      
## [436] "lightslategray"       "lightslategrey"       "lightsteelblue"      
## [439] "lightsteelblue1"      "lightsteelblue2"      "lightsteelblue3"     
## [442] "lightsteelblue4"      "lightyellow"          "lightyellow1"        
## [445] "lightyellow2"         "lightyellow3"         "lightyellow4"        
## [448] "limegreen"            "linen"                "magenta"             
## [451] "magenta1"             "magenta2"             "magenta3"            
## [454] "magenta4"             "maroon"               "maroon1"             
## [457] "maroon2"              "maroon3"              "maroon4"             
## [460] "mediumaquamarine"     "mediumblue"           "mediumorchid"        
## [463] "mediumorchid1"        "mediumorchid2"        "mediumorchid3"       
## [466] "mediumorchid4"        "mediumpurple"         "mediumpurple1"       
## [469] "mediumpurple2"        "mediumpurple3"        "mediumpurple4"       
## [472] "mediumseagreen"       "mediumslateblue"      "mediumspringgreen"   
## [475] "mediumturquoise"      "mediumvioletred"      "midnightblue"        
## [478] "mintcream"            "mistyrose"            "mistyrose1"          
## [481] "mistyrose2"           "mistyrose3"           "mistyrose4"          
## [484] "moccasin"             "navajowhite"          "navajowhite1"        
## [487] "navajowhite2"         "navajowhite3"         "navajowhite4"        
## [490] "navy"                 "navyblue"             "oldlace"             
## [493] "olivedrab"            "olivedrab1"           "olivedrab2"          
## [496] "olivedrab3"           "olivedrab4"           "orange"              
## [499] "orange1"              "orange2"              "orange3"             
## [502] "orange4"              "orangered"            "orangered1"          
## [505] "orangered2"           "orangered3"           "orangered4"          
## [508] "orchid"               "orchid1"              "orchid2"             
## [511] "orchid3"              "orchid4"              "palegoldenrod"       
## [514] "palegreen"            "palegreen1"           "palegreen2"          
## [517] "palegreen3"           "palegreen4"           "paleturquoise"       
## [520] "paleturquoise1"       "paleturquoise2"       "paleturquoise3"      
## [523] "paleturquoise4"       "palevioletred"        "palevioletred1"      
## [526] "palevioletred2"       "palevioletred3"       "palevioletred4"      
## [529] "papayawhip"           "peachpuff"            "peachpuff1"          
## [532] "peachpuff2"           "peachpuff3"           "peachpuff4"          
## [535] "peru"                 "pink"                 "pink1"               
## [538] "pink2"                "pink3"                "pink4"               
## [541] "plum"                 "plum1"                "plum2"               
## [544] "plum3"                "plum4"                "powderblue"          
## [547] "purple"               "purple1"              "purple2"             
## [550] "purple3"              "purple4"              "red"                 
## [553] "red1"                 "red2"                 "red3"                
## [556] "red4"                 "rosybrown"            "rosybrown1"          
## [559] "rosybrown2"           "rosybrown3"           "rosybrown4"          
## [562] "royalblue"            "royalblue1"           "royalblue2"          
## [565] "royalblue3"           "royalblue4"           "saddlebrown"         
## [568] "salmon"               "salmon1"              "salmon2"             
## [571] "salmon3"              "salmon4"              "sandybrown"          
## [574] "seagreen"             "seagreen1"            "seagreen2"           
## [577] "seagreen3"            "seagreen4"            "seashell"            
## [580] "seashell1"            "seashell2"            "seashell3"           
## [583] "seashell4"            "sienna"               "sienna1"             
## [586] "sienna2"              "sienna3"              "sienna4"             
## [589] "skyblue"              "skyblue1"             "skyblue2"            
## [592] "skyblue3"             "skyblue4"             "slateblue"           
## [595] "slateblue1"           "slateblue2"           "slateblue3"          
## [598] "slateblue4"           "slategray"            "slategray1"          
## [601] "slategray2"           "slategray3"           "slategray4"          
## [604] "slategrey"            "snow"                 "snow1"               
## [607] "snow2"                "snow3"                "snow4"               
## [610] "springgreen"          "springgreen1"         "springgreen2"        
## [613] "springgreen3"         "springgreen4"         "steelblue"           
## [616] "steelblue1"           "steelblue2"           "steelblue3"          
## [619] "steelblue4"           "tan"                  "tan1"                
## [622] "tan2"                 "tan3"                 "tan4"                
## [625] "thistle"              "thistle1"             "thistle2"            
## [628] "thistle3"             "thistle4"             "tomato"              
## [631] "tomato1"              "tomato2"              "tomato3"             
## [634] "tomato4"              "turquoise"            "turquoise1"          
## [637] "turquoise2"           "turquoise3"           "turquoise4"          
## [640] "violet"               "violetred"            "violetred1"          
## [643] "violetred2"           "violetred3"           "violetred4"          
## [646] "wheat"                "wheat1"               "wheat2"              
## [649] "wheat3"               "wheat4"               "whitesmoke"          
## [652] "yellow"               "yellow1"              "yellow2"             
## [655] "yellow3"              "yellow4"              "yellowgreen"
#Crear paleta manualmente
Paleta <- c("cadetblue","coral","mediumspringgreen")

p <- ggplot(bd, aes(x=Home.range , y = Mass))+
    geom_point(aes(colour = Diet))+
    scale_colour_manual(values=Paleta)
p

# Colores por posicion
cbPalette <- c(colors()[100], colors()[200] , colors()[40])
b <- ggplot(bd, aes(x=Diet, y = Mass, fill=Diet))+
    geom_bar(stat = "identity") +
    scale_fill_manual(values = cbPalette, 
                      labels=c("label1", "label2", "label3"))
b

#Paleta brewer
display.brewer.all()

ggplot(bd, aes(x=Home.range , y = Mass))+
    geom_point(aes(colour = Diet))+
    scale_color_brewer(palette='Accent') 

#Paleta paletteer
#https://r-charts.com/es/paletas-colores/
#terrain.colors() heat.colors(), topo.colors(), cm.colors(), rainbow().

ggplot(bd, aes(x=Home.range , y = Mass, colour=Mass)) +
    geom_point() +
    scale_colour_gradientn(colours=rainbow(30))

#Crear paleta
p1 <- paletteer_c("ggthemes::Blue-Green Sequential", 30)
ggplot(bd, aes(x=Home.range , y = Mass, colour=Mass))+
    geom_point()+
    scale_colour_gradientn(colours=p1)

p2 <- paletteer_c("grDevices::Inferno", 30)
ggplot(bd, aes(x=Home.range , y = Mass, colour=Mass))+
    geom_point()+
    scale_colour_gradientn(colours=p2)

###sistema de coordenadas####
#Por defecto, los gráficos de ggplot2 tienen coordenadas cartesianas. 
#La función coord_cartesian permite  hacer zoom a los gráficos

range(bd$Home.range) # tener presente el rango va de -4.44 a 5.69
## [1] -4.44  5.69
range(bd$Mass) # -2.38  4.52
## [1] -2.38  4.52
e <- ggplot(data = bd, aes(x = Home.range, y = Mass))
e

e + geom_point()

#Delimitar x
e + geom_point() +
    coord_cartesian(xlim=c(0,3))

e + geom_point() +
    coord_cartesian(ylim=c(0,2))

e + geom_point() +
    coord_cartesian(xlim=c(0,2.5),
                    ylim=c(0,2.5))

#Los sistemas de coordenadas en ggplot2 se pueden dividir en: (coord_cartesian, coord_fixed, coord_flip) y  lineales (coord_trans, coord_polar, coord_quickmap, coord_map). 

#la unidad a lo largo del eje X será la misma unidad a lo largo del eje Y
e + geom_point()+
    coord_cartesian()

#las unidades difieren según los datos de X y y
e + geom_point()+
    coord_fixed()

#Rotar los ejes
f <- ggplot(bd, aes(x=Diet, y = Mass))
f

f + geom_boxplot()+
    coord_flip()

#La función coord_trans crea sistemas sistemas de coordenadas cartesianas transformadas,afectando a la apariencia de los geoms
#Coordenadas polares
f <- ggplot(bd, aes(x=Diet, y = Mass))
f

f + geom_bar(stat = "identity")

f + geom_bar(stat = "identity")+
    coord_polar()

f + geom_bar(stat = "identity")+
    coord_polar(theta = "y")

#################FACETAS#####################################
#La creación de facetas muestra un subconjunto diferente de los datos. 
#Hay tres tipos de facetas:

#facet_null(): un único gráfico, el predeterminado.

#facet_wrap(): "envuelve" los paneles

#facet_grid(): produce una cuadrícula de paneles definidos por variables que forman las filas y columnas.

#facet_grid()
#Columnas
ggplot(data = bd, aes(x = Home.range, y = Mass)) +
    geom_point() +
    facet_grid(~ Diet)

ggplot(data = bd, aes(x = Home.range, y = Mass)) +
  geom_point() +
  facet_grid(~ Diet, scales = "free")

#Filas
ggplot(data = bd, aes(x = Home.range, y = Mass))+
    geom_point()+
    facet_grid(Environment ~ .)

#Filas y columnas#falta agregar una columna cualitativa
ggplot(data = bd, aes(x = Home.range, y = Mass))+
    geom_point()+
    facet_grid(Environment~Diet)

#facet_wrap(): "envuelve" los paneles
head(bd)
##   ID     Gender                   Taxon Home.range  Mass      Diet Environment
## 1  1  Abrothrix    Abrothrix_olivaceus       -3.33 -1.61  Omnivore Terrestrial
## 2  2   Acinonyx       Acinonyx_jubatus        2.91  1.70 Carnivore Terrestrial
## 3  3  Aepyceros     Aepyceros_melampus        0.51  1.80 Herbivore Terrestrial
## 4  4 Ailuropoda Ailuropoda_melanoleuca        0.62  1.94 Herbivore Terrestrial
## 5  5    Ailurus        Ailurus_fulgens        0.01  0.73 Herbivore Terrestrial
## 6  6 Alcelaphus  Alcelaphus_buselaphus        0.34  2.13 Herbivore Terrestrial
ggplot(data = bd, aes(x = Home.range, y = Mass))+
    geom_point()+
    facet_wrap(Environment ~ Diet)

# Juntar varias graficas en una sola figuras (cowplot)
#Mostrar dos gráficas diferentes
graf1 <- ggplot(bd, aes(x=Diet, y = Mass)) + 
    geom_boxplot() +
    geom_jitter()
graf1

graf2 <- ggplot(bd, aes(x=Diet, y = Mass))+ 
    geom_jitter()
graf2

finalgraf <- plot_grid(graf1, graf2, labels=c("A","B"), ncol = 2, nrow = 1)
finalgraf

finalgraf <- plot_grid(graf1, graf2, labels=c("1A","1B"), ncol = 2, nrow = 1)
finalgraf

## Listo! Solo nos queda guardar nuestro grafico
ggsave(filename = paste0(indir, "ggplot2_final.png"), 
       plot = finalgraf,
       width = 10, height = 7, units = "in", #pulgadas
       bg = "white",
       dpi = 300)