Mostrando entradas con la etiqueta plotly. Mostrar todas las entradas
Mostrando entradas con la etiqueta plotly. 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

    2018-08-31

    Gráficos de An Introduction to Statistical Learning con ggplot2 y plotly - Figura 1.4. interactiva

    Problema

    Queremos añadir interactividad al gráfico creado en la entrada anterior, el gráfico de la derecha de la figura 1.4 del libro An Introduction to Statistical Learning. El gráfico representa el conjunto de datos NCI-60, cada tipo de cáncer con un color y símbolo diferente. Las observaciones que corresponden al mismo tipo de cáncer tienden a estar cerca em este espacio bidimensional.

    Solución

    Empleamos el paquete plotly que permite crear gráficos interactivos en la web. En concreto la función de ggplotly que convierte un objeto ggplot2 en un objeto plotly.

    # Librerías y datos NCI60 
    library(ISLR)
    library(tidyverse)
    library(plotly)
    nci.labs <- NCI60$labs
    nci.data <- NCI60$data
    pr.out <- prcomp(nci.data, scale = TRUE)
    
    # Gráfico 2
    df2 <- data.frame(pr.out$x[, 1:2], nci.labs)
    p2 <- ggplot(df2, aes(x = PC1, y = PC2, colour = nci.labs)) +
      geom_point(size = 3)+
      labs(x = "Z1", y = "Z2")+
      theme_bw()+
      theme(legend.position="none")
    
    # Interactividad
    ggplotly(p2)
    

    Entradas relacionadas

    Nube de datos