2017-10-04

Settings

library(plotly)
data(gapminder, package = 'gapminder')
gapminder_continent <- gapminder %>% 
    group_by(continent, year) %>% 
    dplyr::summarise(gdpPercap = median(gdpPercap)) 

ggplot

gapminder %>% filter(country == 'Hungary') %>%
    ggplot(aes(x = year, y = gdpPercap)) + geom_line()

ggplotly

p <- gapminder %>% filter(country == 'Hungary') %>%
    ggplot(aes(x = year, y = gdpPercap)) + geom_line()
ggplotly(p)

plot_ly

gapminder %>% filter(country == 'Hungary') %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% add_lines()

Groups #1: map continent to color

gapminder_continent %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% 
    add_lines(color = ~continent)

Settings: color vs colors

gapminder_continent %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% 
    add_lines(color = ~continent, colors = 'Dark2')

Subplot

gapminder_continent %>%
    mutate(id = as.integer(continent)) %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% 
    add_lines(color = ~continent, yaxis = ~paste0('y', id)) %>%
    subplot(nrows = 5, shareX = TRUE)

Groups #2: understand grouped data.frame

gapminder_continent %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% 
    add_lines()

Modifyer function

plt <- gapminder_continent %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% 
    add_lines(alpha = 0.5, name = 'Continents', hoverinfo = 'none')
plt %>% filter(continent == 'Europe') %>% add_lines(name = 'Europe')

Modifyer function

layer_continent <- function(plot, name) {
    plot %>% filter(continent == name) %>% add_lines(name = name)
}
plt %>% add_fun(layer_continent, 'Europe') %>% add_fun(layer_continent, 'Africa')

Use with shiny

library(shiny)
shinyApp(
    
    ui = fluidPage(
        selectInput(
            "country", "Country:", 
            choices = filter(gapminder, continent == 'Europe')$country,
            multiple = TRUE
        ),
        plotlyOutput("gdp_plot")
    ),
    
    server = function(input, output) {
        <generate-base-plot>
        
        output$gdp_plot <- renderPlotly({
            for (c in input$country) {
                european_countries <- european_countries %>% add_fun(layer_country, c)
            }
            layout(european_countries, hovermode = 'x')
        })
    }
)

Slider

gapminder %>% filter(country == 'Hungary') %>%
    plot_ly(x = ~year, y = ~gdpPercap) %>% add_lines() %>%
    rangeslider()

Animation

gapminder %>%
    plot_ly(x = ~gdpPercap, y = ~lifeExp, size = ~pop) %>%
    add_markers(color = ~continent, frame = ~year, ids = ~country) %>%
    layout(xaxis = list(type = "log"))

Export

p <- gapminder %>%
    plot_ly(x = ~gdpPercap, y = ~lifeExp, size = ~pop) %>%
    add_markers(color = ~continent, frame = ~year, ids = ~country) %>%
    layout(xaxis = list(type = "log"))

html

htmlwidgets::saveWidget(p, 'gapminder.html')

static image

export(p, file = 'gapminder.png')

Thank you