R: {ggplot2}

Dr. Francisco Zambrano

Introducción

Descripción

The ggplot2 hex logo.


{ggplot2} es un sistema para crear gráficos de forma declarativa ,
basado en “The Grammar of Graphics” (Wilkinson, 2005).

Usted proprciona los datos y le dice a {ggplot2} como asignar variables a la estetica (aesthetics),
qué primitivas gráficas usar y él se encarga de los detalles.

Ventajas de {ggplot2}

  • “gramática de gráficos” consistente (Wilkinson 2005)
  • especificación de layout en capas muy flexible
  • sistema temático para pulir la apariencia de la trama
  • muchas funciones adicionales gracias a las extensiones
  • comunidad activa y servicial
Allison Horsts monster illustration of explorative plotting with ggplot2.

Ilustración de Allison Horst

A collection of the versatility of ggplot2 to create basic graphs. All of them use the default grey ggplot2 theme.

ggplot2 Ejemplo en ggplot2.tidyverse.org

Allison Horsts monster illustration of building  data masterpiece ith ggplot2 featuring a little Picasso monster :)

Ilustración de Allison Horst

Vitrina de algunos usos de {ggplot2}

A multi-plot panel of various data visualizations created by the BBC teams.

Colección de gráficos de BBC R Cookbook

A colorful and annotated scatterplot and a custom raincloud plot showing various bill measures of Palmer penguins.

#TidyTuesday Week 2020/31 por Cédric Scherer

A gridded map of Europe showing horizontal stacked bars of energy production per country over time (each bar represents share among one year from 2016 to 2018).

Contribución a #TidyTuesday por Jack Davison

A spatial map of income and inequality shown with a bivariate color palette; alpine regions have a hillshading effect.

Bivariate Choropleth x Hillshade Map by Timo Gossenbacher

Un ejemplo para motivar

Descargar datos de arriendo de bicicletas en Londres

https://drive.google.com/file/d/148sbepxMMmdKbcJV2PEnm1PA98Htg2ej/view?usp=sharing

## scatter plot of plot bikes$count versus bikes$count
ggplot(bikes, aes(temp_feel, count)) +
  geom_point(size = 2.2)

ggplot(bikes, aes(temp_feel, count)) +
  ## colored, semi-transparent points
  geom_point(
    aes(color = season),
    size = 2.2
  )

ggplot(bikes, aes(temp_feel, count)) +
  geom_point(
    aes(color = season),
    size = 2.2
  ) +
  ## add a linear fitting for each time of the day
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  )

ggplot(bikes, aes(temp_feel, count)) +
  geom_point(
    aes(color = season),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  ) +
  ## create small multiples of time of day versus workday
  facet_grid(day_night ~ is_workday)

ggplot(bikes, aes(temp_feel, count)) +
  geom_point(
    aes(color = season),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  ) +
  ## create free-ranging, proportionally sized small multiples
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y", space = "free_y"
  )

ggplot(bikes, aes(temp_feel, count)) +
  geom_point(
    aes(color = season),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  ) +
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y", space = "free_y"
  ) +
  ## add labels + titles
  labs(
    x = "Feels-Like Temperature", y = NULL,
    caption = "Data: TfL (Transport for London), Jan 2015 — Dec 2016",
    title = "Alquileres de bicicletas informados versus la temperatura ambiente en Londres por hora del día, período y temporada."
  )

ggplot(bikes, aes(temp_feel, count)) +
  geom_point(
    aes(color = season),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  ) +
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y", space = "free_y"
  ) +
  ## add custom colors + legend styling
  scale_color_manual(
    values = c("#3c89d9", "#1ec99b", "#F7B01B", "#a26e7c"), name = "Season:",
    guide = guide_legend(override.aes = list(size = 5))
  ) +
  labs(
    x = "Feels-Like Temperature", y = NULL,
    caption = "Data: TfL (Transport for London), Jan 2015 — Dec 2016",
    title = "Alquileres de bicicletas informados versus la temperatura ambiente en Londres por hora del día, período y temporada."
  ) +
  ## use different theme and typeface
  theme_light(base_size = 18, base_family = "Cabinet Grotesk")

## coding for facet strip text
Códigos <- c(
  workday = "Workday",
  weekend_or_holiday = "Weekend or Holiday"
)

ggplot(bikes, aes(temp_feel, count)) +
  ## format seasons
  geom_point(
    aes(color = forcats::fct_relabel(season, stringr::str_to_title)),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night),
    method = "lm", color = "black"
  ) +
  ## format facet strip text
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y", space = "free_y",
    labeller = labeller(
      day_night = stringr::str_to_title,
      is_workday = Códigos
    )
  ) +
  ## customize x axis
  scale_x_continuous(
    expand = c(.02, .02),
    breaks = 0:6*5, labels = function(x) paste0(x, "°C")
  ) +
  ## customize y axis
  scale_y_continuous(
    expand = c(.1, .1), limits = c(0, NA),
    breaks = 0:5*10000, labels = scales::comma_format()
  ) +
  scale_color_manual(
    values = c("#3c89d9", "#1ec99b", "#F7B01B", "#a26e7c"), name = NULL,
    guide = guide_legend(override.aes = list(size = 5))
  ) +
  labs(
    x = "Feels-Like Temperature", y = NULL,
    caption = "Data: TfL (Transport for London), Jan 2015 — Dec 2016",
    title = "Alquileres de bicicletas informados versus la temperatura ambiente en Londres por hora del día, período y temporada."
  ) +
  theme_light(
    base_size = 18, base_family = "Cabinet Grotesk"
  ) +
  ## theme adjustments
  theme(
    plot.title.position = "plot",
    plot.caption.position = "plot",
    plot.title = element_text(face = "bold"),
    strip.text = element_text(face = "bold"),
    legend.position = "top"
  )

Códigos <- c(
  workday = "Workday",
  weekend_or_holiday = "Weekend or Holiday"
)

ggplot(bikes, aes(temp_feel, count)) +
  ## point outline
  geom_point(
    color = "black", fill = "white",
    shape = 21, size = 2.8
  ) +
  ## opaque point background
  geom_point(
    color = "white", size = 2.2
  ) +
  ## colored, semi-transparent points
  geom_point(
    aes(color = forcats::fct_relabel(season, stringr::str_to_title)),
    size = 2.2
  ) +
  geom_smooth(
    aes(group = day_night), method = "lm", color = "black"
  ) +
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y", space = "free_y",
    labeller = labeller(
      day_night = stringr::str_to_title,
      is_workday = Códigos
    )
  ) +
  scale_x_continuous(
    expand = c(.02, .02),
    breaks = 0:6*5, labels = function(x) paste0(x, "°C")
  ) +
  scale_y_continuous(
    expand = c(.1, .1), limits = c(0, NA),
    breaks = 0:5*10000, labels = scales::comma_format()
  ) +
  scale_color_manual(
    values = c("#3c89d9", "#1ec99b", "#F7B01B", "#a26e7c"), name = NULL,
    guide = guide_legend(override.aes = list(size = 5))
  ) +
  labs(
    x = "Feels-Like Temperature", y = NULL,
    caption = "Data: TfL (Transport for London), Jan 2015 — Dec 2016",
    title = "Alquileres de bicicletas informados versus la temperatura ambiente en Londres por hora del día, período y temporada."
  ) +
  theme_light(
    base_size = 18, base_family = "Cabinet Grotesk"
  ) +
  ## more theme adjustments
  theme(
    plot.title.position = "plot",
    plot.caption.position = "plot",
    plot.title = element_text(face = "bold", size = rel(1.3)),
    axis.text = element_text(family = "Tabular"),
    axis.title.x = element_text(hjust = 0, color = "grey30", margin = margin(t = 12)),
    strip.text = element_text(face = "bold" , size = rel(1.15)),
    panel.grid.major.x = element_blank(),
    panel.grid.minor = element_blank(),
    panel.spacing = unit(1.2, "lines"),
    legend.position = "top",
    legend.text = element_text(size = rel(1)),
    ## for fitting my slide background
    legend.key = element_rect(color = "#f8f8f8", fill = "#f8f8f8"),
    legend.background = element_rect(color = "#f8f8f8", fill = "#f8f8f8"),
    plot.background = element_rect(color = "#f8f8f8", fill = "#f8f8f8")
  )

Facetas, escalas, y sistema de coordenadas

Setup

library(tidyverse)

bikes <- readr::read_csv(
  here::here("data", "london-bikes-custom.csv"),
  col_types = "Dcfffilllddddc"
)

bikes$season <- forcats::fct_inorder(bikes$season)

theme_set(theme_light(base_size = 14, base_family = "Roboto Condensed"))

theme_update(
  panel.grid.minor = element_blank(),
  plot.title = element_text(face = "bold"),
  legend.position = "top",
  plot.title.position = "plot"
)

invisible(Sys.setlocale("LC_TIME", "C"))

Facetas (Facets)

Facetas (Facets)


= Separa variables en distintos paneles

Las facetas son conocidas como:

  • small multiples
  • trellis graphs
  • lattice plots
  • conditioning

Setup

g <-
  ggplot(
    bikes,
    aes(x = temp_feel, y = count,
        color = season)
  ) +
  geom_point(
    alpha = .3,
    guide = "none"
  )

g

Wrapped Facets

g +
  facet_wrap(
    vars(day_night)
  )

Wrapped Facets

g +
  facet_wrap(
    ~ day_night
  )

Facet para multiple variables

g +
  facet_wrap(
    ~ is_workday + day_night
  )

Facet opciones: Cols + Rows

g +
  facet_wrap(
    ~ day_night,
    ncol = 1
  )

Facet Opciones: Free Scaling

g +
  facet_wrap(
    ~ day_night,
    ncol = 1,
    scales = "free"
  )

Facet Opciones: Free Scaling

g +
  facet_wrap(
    ~ day_night,
    ncol = 1,
    scales = "free_y"
  )

Facet Opciones: Switch Labels

g +
  facet_wrap(
    ~ day_night,
    ncol = 1,
    switch = "x"
  )

Gridded Facets

g +
  facet_grid(
    rows = vars(day_night),
    cols = vars(is_workday)
  )

Gridded Facets

g +
  facet_grid(
    day_night ~ is_workday
  )

Facet para Multiples Variables

g +
  facet_grid(
    day_night ~ is_workday + season
  )

Facet Opciones: Free Scaling

g +
  facet_grid(
    day_night ~ is_workday,
    scales = "free"
  )

Facet Opciones: Cambiar Labels

g +
  facet_grid(
    day_night ~ is_workday,
    scales = "free",
    switch = "y"
  )

Facet Opciones: Espacio proporcional

g +
  facet_grid(
    day_night ~ is_workday,
    scales = "free",
    space = "free"
  )

Facet Options: Espacio proporcional

g +
  facet_grid(
    day_night ~ is_workday,
    scales = "free_y",
    space = "free_y"
  )

Tu turno!

Crea el siguiente facet desde el set de datos de diamonds.

Tu turno!

Bonus: Crea esta versión oscura.

Diamonds Facet

ggplot(
    diamonds,
    aes(x = carat, y = price)
  ) +
  geom_point(
    alpha = .3
  ) +
  geom_smooth(
    method = "lm",
    se = FALSE,
    color = "dodgerblue"
  )

Diamonds Facet

ggplot(
    diamonds,
    aes(x = carat, y = price)
  ) +
  geom_point(
    alpha = .3
  ) +
  geom_smooth(
    method = "lm",
    se = FALSE,
    color = "dodgerblue"
  ) +
  facet_grid(
    cut ~ clarity,
    space = "free_x",
    scales = "free_x"
  )

Diamonds Facet (Bonus tema oscuro)

ggplot(
    diamonds,
    aes(x = carat, y = price)
  ) +
  geom_point(
    alpha = .3,
    color = "white"
  ) +
  geom_smooth(
    method = "lm",
    se = FALSE,
    color = "dodgerblue"
  ) +
  facet_grid(
    cut ~ clarity,
    space = "free_x",
    scales = "free_x"
  ) +
  theme_dark(
    base_size = 14,
    base_family = "Roboto Condensed"
  )

Escalas (Scales)

Scales


= traducir entre rangos de variables y rangos de propiedades

  • senación térmica  ⇄  x
  • bicicletas compartidas reportadas  ⇄  y
  • temporada  ⇄  color
  • año  ⇄  shape
  • …

Scales

La componente scale_*() controla las propiedades de todos las
dimensiones de la estética graficadas de los datos.


Consecuentemente, existe la función scale_*() para todas las estéticas (astethics):

  • positions con scale_x_*() y scale_y_*()

  • colors con scale_color_*() y scale_fill_*()

  • sizes con scale_size_*() y scale_radius_*()

  • shapes con scale_shape_*() y scale_linetype_*()

  • transparency con scale_alpha_*()

Scales

La componente scale_*() controla las propiedades de todos las
dimensiones de la estética graficadas de los datos.


La extensión (*) puede ser completada por:

  • continuous(), discrete(), reverse(), log10(), sqrt(), date() para posiciones

  • continuous(), discrete(), manual(), gradient(), gradient2(), brewer() para colores

  • continuous(), discrete(), manual(), ordinal(), area(), date() para tamaños

  • continuous(), discrete(), manual(), ordinal() para formas

  • continuous(), discrete(), manual(), ordinal(), date() para transparencia

Allison Horsts illustration ofthe correct use of continuous versus discrete; however, in {ggplot2} these are interpeted in a different way: as quantitative and qualitative.

Ilustración de Allison Horst

Continua vs. Discreta en {ggplot2}

Continua:
datos cuantitativos o numéricos

  • tamaño
  • peso
  • edad
  • conteo

Discreta:
datos cualitativos o categóricos

  • especies
  • sexo
  • sitios de estudio
  • rango de edad

Continuo vs. Discreto en {ggplot2}

Continuo:
datos cuantitativos o numéricos

  • tamaño (continuo)
  • peso (continuo)
  • edad (continuo o discreto)
  • conteo (discreto)

Discreto:
datos cualitativos o categóricos

  • especies (nominal)
  • sexo (nominal)
  • sitio de estudio (nominal or ordinal)
  • rango de edad (ordinal)

Aesthetics + Scales

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point()

Aesthetics + Scales

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_date() +
  scale_y_continuous() +
  scale_color_discrete()

Scales

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_continuous() +
  scale_y_continuous() +
  scale_color_discrete()

Scales

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_continuous() +
  scale_y_log10() +
  scale_color_discrete()

Scales

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_continuous() +
  scale_y_log10() +
  scale_color_viridis_d()

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +  
  geom_point() +
  scale_y_continuous(
    trans = "log10"
  )

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares"
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = seq(0, 60000, by = 15000)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = 0:4*15000
  )

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = c(0, 2:12*2500, 40000, 50000)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares in thousands",
    breaks = 0:4*15000,
    labels = 0:4*15
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares in thousands",
    breaks = 0:4*15000,
    labels = paste(0:4*15000, "bikes")
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = 0:4*15000,
    limits = c(NA, 60000)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = 0:4*15000,
    expand = c(0, 0)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = -1:5*15000,
    expand = c(.5, .5) ## c(add, mult)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = -1:5*15000,
    expand = expansion(add = 2000)
  ) 

`scale_x|y_continuous`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_y_continuous(
    name = "Reported bike shares",
    breaks = 0:4*15000,
    guide = "none"
  )

`scale_x|y_date`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_date(
    name = NULL,
    date_breaks = "4 months"
  )

`scale_x|y_date`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_date(
    name = NULL,
    date_breaks = "20 weeks"
  )

`scale_x|y_date` con `strftime()`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_date(
    name = NULL,
    date_breaks = "6 months",
    date_labels = "%Y/%m/%d"
  )

`scale_x|y_date` con `strftime()`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_x_date(
    name = NULL,
    date_breaks = "6 months",
    date_labels = "%b '%y"
  )

`scale_x|y_discrete`

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  scale_x_discrete(
    name = "Period",
    labels = c("Dec-Feb", "Mar-May", "Jun-Aug", "Sep-Nov")
  )

`scale_x|y_discrete`

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  scale_x_discrete(
    name = "Season",
    expand = c(.5, 0) ## add, mult
  )

¿Discreto o continuo?

ggplot(
    bikes,
    aes(x = as.numeric(season), y = count)
  ) +
  geom_boxplot(
    aes(group = season)
  )

¿Discreto o continuo?

ggplot(
    bikes,
    aes(x = as.numeric(season),
        y = count)
  ) +
  geom_boxplot(
    aes(group = season)
  ) +
  scale_x_continuous(
    name = "Season",
    breaks = 1:4,
    labels = levels(bikes$season)
  )

¿Discreto o continuo?

ggplot(
    bikes,
    aes(x = as.numeric(season) + 
            as.numeric(season) / 8,
        y = count)
  ) +
  geom_boxplot(
    aes(group = season)
  ) +
  scale_x_continuous(
    name = "Season",
    breaks = 1:4,
    labels = levels(bikes$season)
  )

`scale_color|fill_discrete`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_color_discrete(
    name = "Season:",
    type = c("#69b0d4", "#00CB79", "#F7B01B", "#a78f5f")
  )

Inspeccionar los colores asignados

g <- ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_color_discrete(
    name = "Season:",
    type = c("#3ca7d9", "#1ec99b", "#F7B01B", "#bb7e8f")
  )

gb <- ggplot_build(g)

gb$data[[1]][c(1:5, 200:205, 400:405), 1:5]
     colour     x     y PANEL group
1   #3ca7d9 16439  6830     1     1
2   #3ca7d9 16439  2404     1     1
3   #3ca7d9 16440 14763     1     1
4   #3ca7d9 16440  5609     1     1
5   #3ca7d9 16441 14501     1     1
200 #1ec99b 16538  8830     1     2
201 #1ec99b 16539 24019     1     2
202 #1ec99b 16539 10500     1     2
203 #1ec99b 16540 25640     1     2
204 #1ec99b 16540 11830     1     2
205 #1ec99b 16541 22216     1     2
400 #F7B01B 16638 12079     1     3
401 #F7B01B 16639 26646     1     3
402 #F7B01B 16639 12446     1     3
403 #F7B01B 16640 11312     1     3
404 #F7B01B 16640  4722     1     3
405 #F7B01B 16641 22748     1     3

`scale_color|fill_discrete`

my_colors <- c(
  `winter` = "#3c89d9",
  `spring` = "#1ec99b",
  `summer` = "#F7B01B",
  `autumn` = "#a26e7c"
)

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_color_discrete(
    name = "Season:",
    type = my_colors
  )

`scale_color|fill_discrete`

my_colors_alphabetical <- c(
  `autumn` = "#a26e7c",
  `spring` = "#1ec99b",
  `summer` = "#F7B01B",
  `winter` = "#3c89d9"
)

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_color_discrete(
    name = "Season:",
    type = my_colors_alphabetical
  )

`scale_color|fill_discrete`

library(RColorBrewer)

ggplot(
    bikes,
    aes(x = date, y = count,
        color = season)
  ) +
  geom_point() +
  scale_color_discrete(
    name = "Season:",
    type = brewer.pal(
      n = 4, name = "Dark2"
    )
  )

`scale_color|fill_manual`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = weather_type)
  ) +
  geom_point() +
  scale_color_manual(
    name = "Season:",
    values = brewer.pal(n = 6, name = "Pastel1"),
    na.value = "black"
  )

`scale_color|fill_carto_d`

ggplot(
    bikes,
    aes(x = date, y = count,
        color = weather_type)
  ) +
  geom_point() +
  rcartocolor::scale_color_carto_d(
    name = "Season:",
    palette = "Pastel",
    na.value = "black"
  )

Tú turno!

Modifica los facet de diamond de esta forma:

Diamonds Facet

facet <-
  ggplot(
    diamonds,
    aes(x = carat, y = price)
  ) +
  geom_point(
    alpha = .3
  ) +
  geom_smooth(
    aes(color = cut),
    method = "lm",
    se = FALSE
  ) +
  facet_grid(
    cut ~ clarity,
    space = "free_x",
    scales = "free_x"
  )

facet

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = c("$0", "$10,000", "$20,000", "$30,000")
  )

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = paste0(
      "$", format(
        0:3*10000, 
        big.mark = ",", 
        trim = TRUE
      )
    )
  )

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = function(y) paste0(
      "$", format(
        y, big.mark = ",",
        trim = TRUE
      )
    )
  )

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = scales::dollar_format()
  )

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = scales::dollar_format()
  ) +
  scale_color_brewer(
    palette = "Set2",
    guide = "none"
  )

Diamonds Facet

facet +
  scale_x_continuous(
    breaks = 0:5
  ) +
  scale_y_continuous(
    limits = c(0, 30000),
    breaks = 0:3*10000,
    labels = scales::dollar_format()
  ) +
  scale_color_brewer(
    palette = "Set2"
  ) +
  theme(
    legend.position = "none"
  )

Sistema de coordenadas

Sistema de coordenadas


=interpretar la posición de la estética

  • sistemas de coordenadas lineales: preserva la forma geométrica
    • coord_cartesian()
    • coord_fixed()
    • coord_flip()
  • sistemas de coordenadas no-lineales: cambia la forma geométrica
    • coord_polar()
    • coord_map() y coord_sf()
    • coord_trans()

Sistema de coordenadas cartesiano

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  coord_cartesian()

Sistema de coordenadas cartesiano

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  coord_cartesian(
    ylim = c(NA, 15000)
  )

Cambiando límites

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  coord_cartesian(
    ylim = c(NA, 15000)
  )

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  scale_y_continuous(
    limits = c(NA, 15000)
  )

Recortar

ggplot(
    bikes,
    aes(x = season, y = count)
  ) +
  geom_boxplot() +
  coord_cartesian(
    ylim = c(NA, 15000),
    clip = "off"
  )

Recortar

ggplot(
    filter(bikes, is_holiday == TRUE),
    aes(x = temp_feel, y = count)
  ) +
  geom_point() +
  geom_text(
    aes(label = season),
    nudge_x = .3,
    hjust = 0
  ) +
  coord_cartesian(
    clip = "off"
  )

… o mejor usar {ggrepel}

ggplot(
    filter(bikes, is_holiday == TRUE),
    aes(x = temp_feel, y = count)
  ) +
  geom_point() +
  ggrepel::geom_text_repel(
    aes(label = season),
    nudge_x = .3,
    hjust = 0
  ) +
  coord_cartesian(
    clip = "off"
  )

Quitar todo el relleno

ggplot(
    bikes,
    aes(x = temp_feel, y = count)
  ) +
  geom_point() +
  coord_cartesian(
    expand = FALSE,
    clip = "off"
  )

Sistema de coordenada fijo

ggplot(
    bikes,
    aes(x = temp_feel, y = temp)
  ) +
  geom_point() +
  coord_fixed()

ggplot(
    bikes,
    aes(x = temp_feel, y = temp)
  ) +
  geom_point() +
  coord_fixed(ratio = 4)

Sistema de coordenadas invertido

ggplot(
    bikes,
    aes(x = weather_type)
  ) +
  geom_bar() +
  coord_cartesian()

ggplot(
    bikes,
    aes(x = weather_type)
  ) +
  geom_bar() +
  coord_flip()

Sistema de coordenadas invertido

ggplot(
    bikes,
    aes(y = weather_type)
  ) +
  geom_bar() +
  coord_cartesian()

ggplot(
    bikes,
    aes(x = weather_type)
  ) +
  geom_bar() +
  coord_flip()

Recordatorio: ¡Ordene sus barras!

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(y = fct_infreq(weather_type))
  ) +
  geom_bar()

Recordatorio: ¡Ordene sus barras!

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(y = fct_rev(
      fct_infreq(weather_type)
    ))
  ) +
  geom_bar()

Sistema de coordenadas circular

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = weather_type,
        fill = weather_type)
  ) +
  geom_bar() +
  coord_polar()

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = weather_type,
        fill = weather_type)
  ) +
  geom_bar() +
  coord_cartesian()

Sistema de coordenadas circular

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = fct_infreq(weather_type),
        fill = weather_type)
  ) +
  geom_bar(width = 1) +
  coord_polar()

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = fct_infreq(weather_type),
        fill = weather_type)
  ) +
  geom_bar(width = 1) +
  coord_cartesian()

Sistema de coordenadas circular

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = fct_infreq(weather_type),
        fill = weather_type)
  ) +
  geom_bar() +
  coord_polar(theta = "x")

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = fct_infreq(weather_type),
        fill = weather_type)
  ) +
  geom_bar() +
  coord_polar(theta = "y")

Sistema de coordenadas circular

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = 1, fill = weather_type)
  ) +
  geom_bar(position = "stack") +
  coord_polar(theta = "y") 

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = 1, fill = weather_type)
  ) +
  geom_bar(position = "stack") +
  coord_cartesian() 

Sistema de coordenadas circular

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = 1,
        fill = fct_rev(fct_infreq(weather_type)))
  ) +
  geom_bar(position = "stack") +
  coord_polar(theta = "y") +
  scale_fill_discrete(name = NULL)

ggplot(
    filter(bikes, !is.na(weather_type)),
    aes(x = 1,
        fill = fct_rev(fct_infreq(weather_type)))
  ) +
  geom_bar(position = "stack") +
  coord_cartesian() +
  scale_fill_discrete(name = NULL)

Transformar un sistema de coordenadas

ggplot(
    bikes,
    aes(x = temp, y = count)
  ) +
  geom_point() +
  coord_trans(y = "log10")

Transformar un sistema de coordenadas

ggplot(
    bikes,
    aes(x = temp, y = count,
        group = day_night)
  ) +
  geom_point() +
  geom_smooth(method = "lm") +
  coord_trans(y = "log10")

ggplot(
    bikes,
    aes(x = temp, y = count,
        group = day_night)
  ) +
  geom_point() +
  geom_smooth(method = "lm") +
  scale_y_log10()

Recapitulando

  • facet_*() función que permite crear paneles
  • scale_*() función que traduce entre los aesthetics y sus propiedades
  • use *_continuous() para datos numéricos
  • … y *_discrete() para datos categóricos
  • use scale_color|fill_*() para customizar los colores
  • coord_*() funciones que interpretan la posición de los aesthetics
    • ej. crear gráficos con coordenadas polares con proyecciones espaciales
  • tenga cuidado cuando ajuste los límites de los ejes:
    • scale_*_continuous(limits) remueve los datos fuera de los límites
    • coord_*(*lim) mantiene los datos y zoom dentro de un rango