Mostrando entradas con la etiqueta facet_wrap. Mostrar todas las entradas
Mostrando entradas con la etiqueta facet_wrap. Mostrar todas las entradas

2020-04-03

Creación de gráficos del coronavirus en R

Introducción

Queremos mostrar la evolución de casos de coronavirus en R con gráficos estáticos e interactivos.

Gráficos

  • Interactivo (escala lineal)
  • Interactivo (escala logaritmica)
  • Solución

    Usamos los datos del repositorio creado por Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE). Hay tres series de datos temporales: confirmed, deaths y recovered cases. Primero preparamos los datos y creamos el gráfico usando ggplot2 para la versión estática, y plotly para añadir interactividad. Las series de datos incluyen casos de todo el mundo pero en nuestro ejemplo usamos un subconjunto para Alemania, Francia, Italia, España y el Reino Unido.

    # Librerias
    library(magrittr)
    library(lubridate) 
    library(tidyverse)
    library(plotly)
    library(scales)
    
    # Importación de datos
    confirmed <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
    deaths <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv")
    recovered <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv")
    
    # Data preparation
    AppendMe <- function(dfNames) {
      do.call(rbind, lapply(dfNames, function(x) {
        cbind(get(x), source = x)
      }))
    }
    df <- AppendMe(c("confirmed", "deaths", "recovered"))
    data <- df %>%
      rename(province = `Province/State`, country = `Country/Region`) %>% 
      pivot_longer(
        -c(province, country, Lat, Long, source),
        names_to = "date",
        values_to = "count"
      ) %>% 
    mutate(date = mdy(date)) 
    
    # Gráfico escala lineal
    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(n = sum(count)) %>%
      ggplot(aes(date, n, colour = country)) +
      geom_line(linetype = 2) +
      geom_point(size = 1) +
      facet_wrap( ~  source  , scales = "free", nrow = 3) +
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (linear scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_continuous(labels = comma)
    p # Estático
    ggplotly(p) # Interactivo
    
    # Gráfico escala logaritmica
    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(n = sum(count)) %>%
      ggplot(aes(date, n, colour = country)) +
      geom_line(linetype = 2) +
      geom_point(size = 1) +
      facet_wrap( ~  source, scales = "free",  nrow = 3) +
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (log scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_log10(breaks = c(1, 10, 100, 10000))
      p 
    ggplotly(p) 
    
    Para subrayar una serie al pasar sobre ella usamos la función highlight del paquete plotly.

    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(cases = sum(count)) %>%
      highlight_key(~ country ) %>% 
      ggplot(aes(date, cases, colour = country)) +
      geom_line(linetype = 2)+
      geom_point(size = 1) +
      facet_wrap(~  source  , scales = "free", nrow = 3)+
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (linear scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_continuous(labels = comma)
    ggplotly(p, tooltip = c("country", "date", "cases")) %>% 
    highlight(on = "plotly_hover")
    
    Gráficco here. Pantallazo abajo.

    Referencias

    2020-03-20

    Plotting coronavirus cases in R

    Introduction

    We want to show the evolution of the coronavirus cases using R creating static and interactive plots.

    Plots

  • Interactive (linear scale)
  • Interactive (log scale)
  • Solution

    We use the data repository created by Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE). There are three time-series: confirmed, deaths and recovered cases. First we will prepare the data and then plot the time-series using ggplot2 for the static version and plotly to add interactivity. The data source includes cases across the world, but in our example we will subset the time-series for Germany, France, Italy, Spain, and the United Kingdom.

    # Libraries
    library(magrittr)
    library(lubridate) 
    library(tidyverse)
    library(plotly)
    library(scales)
    
    # Importing data
    confirmed <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
    deaths <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv")
    recovered <- read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv")
    
    # Data preparation
    AppendMe <- function(dfNames) {
      do.call(rbind, lapply(dfNames, function(x) {
        cbind(get(x), source = x)
      }))
    }
    df <- AppendMe(c("confirmed", "deaths", "recovered"))
    data <- df %>%
      rename(province = `Province/State`, country = `Country/Region`) %>% 
      pivot_longer(
        -c(province, country, Lat, Long, source),
        names_to = "date",
        values_to = "count"
      ) %>% 
    mutate(date = mdy(date)) 
    
    # Plot linear scale
    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(n = sum(count)) %>%
      ggplot(aes(date, n, colour = country)) +
      geom_line(linetype = 2) +
      geom_point(size = 1) +
      facet_wrap( ~  source  , scales = "free", nrow = 3) +
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (linear scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_continuous(labels = comma)
    p # Static
    ggplotly(p) # Interactive
    
    # Plot log scale
    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(n = sum(count)) %>%
      ggplot(aes(date, n, colour = country)) +
      geom_line(linetype = 2) +
      geom_point(size = 1) +
      facet_wrap( ~  source, scales = "free",  nrow = 3) +
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (log scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_log10(breaks = c(1, 10, 100, 10000))
      p 
    ggplotly(p) 
    
    To highlight a series while hovering over it, we use the function highlightfrom the plotly package.

    p <- data %>%
      filter(country %in% c("Germany", "France", "Italy",  "Spain", "United Kingdom")) %>% 
      group_by(country, date, source) %>%
      summarise(cases = sum(count)) %>%
      highlight_key(~ country ) %>% 
      ggplot(aes(date, cases, colour = country)) +
      geom_line(linetype = 2)+
      geom_point(size = 1) +
      facet_wrap(~  source  , scales = "free", nrow = 3)+
      theme_bw()+
      labs(title = "Cumulative Covid-19 cases (linear scale)")+
      ylab("")+
      scale_x_date(date_labels = "%b %d")+
      scale_y_continuous(labels = comma)
    ggplotly(p, tooltip = c("country", "date", "cases")) %>% 
    highlight(on = "plotly_hover")
    
    Plot here. Screenshot below.

    References

    2019-04-08

    Quantile-quantile (Q-Q) plots with ggplot2

    Problem

    We'd like to create quantile-quantile (Q-Q) plots using ggplot2.

    Solution

    • Option 1: one column.
    • We create two examples using one column of a data frame. In the first example, we previously transform the vector rivers into a data frame. In the second, we use the column Volume from the data frame trees.

      library(tidyverse)
      ggplot(data.frame(rivers), aes(sample = rivers)) + stat_qq() + stat_qq_line()
      ggplot(trees, aes(sample = Volume)) + stat_qq() + stat_qq_line()
      
    • Option 2: multiple columns.
    • We compare the distribution of Miles/(US) gallon by number of cylinders (cyl).

      ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) +
        stat_qq() +
        stat_qq_line()
      
    • Option 3: multiple panels.
    • In this first example no transformation is needed because a column of the data frame contains the groups..

      ggplot(mtcars, aes(sample = mpg)) +
        facet_wrap( ~ factor(cyl)) +
        stat_qq() +
        stat_qq_line()
      
      In the second example, we convert the data frame from wide format to long format for faceting into multiple panels with facet_wrap. Instead of 31 observations for 3 variables, we will have one column condition containing 93 observaciones for the 3 variables.

      gather(trees, condition, measurement, Girth:Volume, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement)) +
        facet_wrap( ~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      
      In the third example, we convert from wide to long, facet by chemical composition, and use a colour for each kiln.

      library(HSAUR2)
      gather(pottery, condition, measurement, Al2O3:BaO, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement, colour = kiln)) +
        facet_wrap(~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      

    References

    2019-03-09

    Gráficos Q-Q con ggplot2

    Problema

    En entradas anteriores explicamos como crear un gráfico Q-Q con el paquete stats preinstalado por defecto. En esa ocasión mostraremos cómo crear estos gráficos con ggplot2.

    Solución

    • Opción 1: única columna.
    • Creamos dos ejemplos de una sola columna de un data frame. En el primero el vector rivers que transformamos previamente en un data frame, y en el segundo la columna Volume del data frame trees.

      library(tidyverse)
      ggplot(data.frame(rivers), aes(sample = rivers)) + stat_qq() + stat_qq_line()
      ggplot(trees, aes(sample = Volume)) + stat_qq() + stat_qq_line()
      
    • Opción 2: múltiples columnas.
    • Comparamos las distribuciones de Miles/(US) gallon por número de cilindros (cyl).

      ggplot(mtcars, aes(sample = mpg, colour = factor(cyl))) +
        stat_qq() +
        stat_qq_line()
      
    • Opción 3: múltiples paneles.
    • En este primer ejemplo no es necesario realizar ninguna transformación porque el data frame tiene una columna con los grupos.

      ggplot(mtcars, aes(sample = mpg)) +
        facet_wrap( ~ factor(cyl)) +
        stat_qq() +
        stat_qq_line()
      
      En este segundo ejemplo transformamos el data frame de formato ancho a largo para poder crear los paneles con facet_wrap. En lugar de tener 31 observaciones para 3 variables, tendremos una columna condition con las 3 variables y 93 observaciones.

      gather(trees, condition, measurement, Girth:Volume, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement)) +
        facet_wrap( ~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      
      En este tercer ejemplo empleamos múltiples colores en función del kiln en cada panel por sustancia química encontrada.

      library(HSAUR2)
      gather(pottery, condition, measurement, Al2O3:BaO, factor_key = TRUE) %>%
        ggplot(aes(sample = measurement, colour = kiln)) +
        facet_wrap(~ condition, scales = "free") +
        stat_qq() +
        stat_qq_line()
      

    Entradas relacionadas

    Referencias

    2019-01-10

    Loops with ggplot2

    Problem

    We want to create a loop and save plots for each subset of data using ggplot2. Instead of plotting on the same panel using facet_wrap o facet_grid, we'd like to display and save eachplot separately.

    library(tidyverse)
    p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
    p + facet_wrap(vars(Species), scales = "free")
    

    Solution

    We create an empty list to store all plots. Then, we start a loop for each unique element of the variable (column) Species. To keep the same title format, we leave the function facet_wrap.

    # Loop
    plots <- list() # Empty list
    p_list <- unique(iris$Species)
    for (i in seq_along(p_list)) {
      # Plot for each Species
      p <- iris %>% filter(Species == p_list[i]) %>%
        ggplot(aes(Sepal.Length, Sepal.Width)) +
        geom_point() +
        facet_wrap( ~ Species) # Títulos
      plots[[i]] = p
      print(p)
    }
    
    To print the whole plot list or a specific element:

    # Print list
    print(plots)
    # Print an element of the list
    print(plots[[1]])
    

    Related posts

    References

    2019-01-09

    Usar bucles en ggplot2

    Problema

    Queremos crear y guardar gráficos separadamente con ggplot2. Es decir, en lugar de mostrar los gráficos en un mismo panel con facet_wrap o facet_grid, queremos crear gráficos independientes, cada uno en un panel y almacenarlos en una lista.

    library(tidyverse)
    p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
    p + facet_wrap(vars(Species), scales = "free")
    

    Solución

    Creamos una lista vacía donde almacenaremos los gráficos. Iniciamos un bucle generando uno gráfico con ggplot2 para cada elemento único de la lista de especies. Dejamos la función facet_wrap, aunque cada gráfico está en un único panel, para obtener el título de cada especie.

    # Bucle
    plots <- list() # Creamos una lista vacía
    p_list <- unique(iris$Species)
    for (i in seq_along(p_list)) {
      # Gráfico por especie
      p <- iris %>% filter(Species == p_list[i]) %>%
        ggplot(aes(Sepal.Length, Sepal.Width)) +
        geom_point() +
        facet_wrap( ~ Species) # Títulos
      plots[[i]] = p
      print(p)
    }
    
    Para volver a imprimir la lista completa de gráficos o uno específico.

    # Imprime lista completa
    print(plots)
    # Imprime uno específico
    print(plots[[1]])
    

    Entradas relacionadas

    Referencias

    Nube de datos