Custom controls and transformations using plotly

Los ejemplos son tomados de la página oficial de plotly, principalmente se obtienen algunos ejemplos gráficos de plotly.

Librerías

Transforms

Filter

Basic example

\[\text{Filter }\rightarrow y_{hp}>\bar{x_{qsec}}\]

Group by

Aggregations

Function Description
count Returns the quantity of items for each group.
sum Returns the summation of all numeric values.
avg Returns the average of all numeric values.
median Returns the median of all numeric values.
mode Returns the mode of all numeric values.
rms Returns the rms of all numeric values.
stddev Returns the standard deviation of all numeric values.
min Returns the minimum numeric value for each group.
max Returns the maximum numeric value for each group.
first Returns the first numeric value for each group.
last Returns the last numeric value for each group.

Basic Example

Aggregate Functions

Histogram Binning

Mapping with Aggregations

Buttons

Methods

El método updatemenu determina qué función de plotly.js se utilizará para modificar el gráfico. Hay 4 métodos posibles:

restyle: modificar datos o atributos de datos
relayout: modificar atributos de diseño
update: modificar datos y atributos de diseño
animate: iniciar o pausar una animación (solo disponible sin conexión)

Restyle Buttons

El método restyle debe usarse al modificar los datos y los atributos de los datos del gráfico. Actualizar un atributo de datos en este ejemplo muestra cómo actualizar un solo atributo de datos: color de línea con el método restyle.

Update Buttons

Actualizar varios atributos de datos. En este ejemplo muestra cómo actualizar varios atributos de datos: escala de color, tipo de gráfico y escala de color con el método restyle.

Relayout Button

El método de “relayout” debe utilizarse al modificar los atributos de diseño del gráfico. Actualizar un atributo de diseño en este ejemplo muestra cómo actualizar un atributo de diseño: formas con el método relayout.

x0 <- rnorm(400, mean=2, sd=0.4)
y0 <- rnorm(400, mean=2, sd=0.4)
x1 <- rnorm(400, mean=3, sd=0.6)
y1 <- rnorm(400, mean=6, sd=0.4)
x2 <- rnorm(400, mean=4, sd=0.2)
y2 <- rnorm(400, mean=4, sd=0.4)

# shapes components
cluster0 = list(type = 'circle',
                xref ='x', 
                yref='y',
                x0=min(x0), 
                y0=min(y0),
                x1=max(x0),
                y1=max(y0),
                opacity=0.25,
                line = list(color="#835AF1"),
                fillcolor="#835AF1")

cluster1 = list(type = 'circle',
                xref ='x', 
                yref='y',
                x0=min(x1),
                y0=min(y1),
                x1=max(x1), 
                y1=max(y1),
                opacity=0.25,
                line = list(color="#7FA6EE"),
                fillcolor="#7FA6EE")
cluster2 = list(type = 'circle',
                xref ='x', 
                yref='y',
                x0=min(x2), 
                y0=min(y2),
                x1=max(x2), 
                y1=max(y2),
                opacity=0.25,
                line = list(color="#B8F7D4"),
                fillcolor="#B8F7D4")

# updatemenus component
updatemenus <- list(list(active = -1,
                         type = 'buttons',
                         buttons = list(list(label = "None",
                                             method = "relayout",
                                             args = list(list(shapes = c()))),
                                        list(label = "Cluster 0",
                                             method = "relayout",
                                             args = list(list(shapes = list(cluster0, c(), c())))),
                                        list(label = "Cluster 1",
                                             method = "relayout",
                                             args = list(list(shapes = list(c(), cluster1, c())))),
                                        list(label = "Cluster 2",
                                             method = "relayout",
                                             args = list(list(shapes = list(c(), c(), cluster2)))),
                                        list(label = "All",
                                             method = "relayout",
                                             args = list(list(shapes = list(cluster0,cluster1,cluster2)))))))

p <- plot_ly(type = 'scatter', 
              mode='markers') %>% 
        add_trace(x=x0, 
                    y=y0, 
                      mode='markers', 
                        marker=list(color='#835AF1')) %>% 
        add_trace(x=x1, 
                    y=y1, 
                      mode='markers', 
                        marker=list(color='#7FA6EE')) %>%
        add_trace(x=x2, 
                    y=y2, 
                      mode='markers', 
                        marker=list(color='#B8F7D4')) %>% 
            layout(title = "Highlight Clusters", 
                      showlegend = FALSE,
                        updatemenus = updatemenus)
p

Update Button

El método update debe usarse al modificar las secciones de datos y diseño del gráfico. Este ejemplo se muestra cómo actualizar los gráficos que se muestran mientras se actualizan simultáneamente los atributos de diseño, como el título del gráfico y las anotaciones.

library(quantmod)
d <- quantmod::getSymbols("AAPL")
df <- data.frame(Date=index(AAPL),coredata(AAPL))

high_annotations <- list(x=df$Date[df$AAPL.High == max(df$AAPL.High)], 
                         y=max(df$AAPL.High),
                         xref='x', 
                         yref='y',
                         text=paste0('High: $',max(df$AAPL.High)),
                         ax=0, 
                         ay=-40)

low_annotations <- list(x=df$Date[df$AAPL.Low == min(df$AAPL.Low)], 
                        y=min(df$AAPL.Low),
                        xref='x', 
                        yref='y',
                        text=paste0('Low: $',min(df$AAPL.Low)),
                        ax=0, 
                        ay=40)

# updatemenus component
updatemenus <- list(list(active = -1,
                         type= 'buttons',
                          buttons = list(list(label = "High",
                                              method = "update",
                                              args = list(list(visible = c(FALSE, TRUE)),
                                                          list(title = "Apple High",
                                                               annotations = list(c(), high_annotations)))),
                                         list(label = "Low",
                                              method = "update",
                                              args = list(list(visible = c(TRUE, FALSE)),
                                                          list(title = "Apple Low",
                                                               annotations = list(low_annotations, c())))),
                                         list(label = "Both",
                                              method = "update",
                                              args = list(list(visible = c(TRUE, TRUE)),
                                                          list(title = "Apple",
                                                               annotations = list(low_annotations, high_annotations)))),
                                         list(label = "Reset",
                                              method = "update",
                                              args = list(list(visible = c(TRUE, TRUE)),
                                                          list(title = "Apple",
                                                               annotations = list(c(), c())))))))

p <- df %>% 
      plot_ly(type = 'scatter', 
                mode = 'lines') %>% 
        add_lines(x = ~Date, 
                    y = ~AAPL.High, 
                      name = "High",
                        line = list(color="#33CFA5")) %>% 
        add_lines(x = ~Date, 
                    y = ~AAPL.Low, 
                      name = "Low",
                        line = list(color="#F06A6A")) %>% 
          layout(title = "Apple", 
                  showlegend = FALSE,
                    xaxis = list(title = "Date"),
                      yaxis = list(title = "Price ($)"),
                        updatemenus = updatemenus)
p

Range Sliders and Selectors

Basic Range Slider and Selector Buttons

## [1] "AAPL" "MSFT"

Sliders

Basic Slider Control

Sine Wave Slider

Mulitple Slider Control

df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/globe_contours.csv') %>%
        mutate(id = seq_len(nrow(.))) %>%
          gather(key, value, -id) %>%
            separate(key, c("l", "line"), "\\.") %>%
              spread(l, value)

geo <- list(showland = TRUE,
            showlakes = TRUE,
            showcountries = TRUE,
            showocean = TRUE,
            countrywidth = 0.5,
            landcolor = 'rgb(230, 145, 56)',
            lakecolor = 'rgb(0, 255, 255)',
            oceancolor = 'rgb(0, 255, 255)',
            projection = list(type = 'orthographic',
                              rotation = list(lon = -100,
                                              lat = 40,
                                              roll = 0)),
            lonaxis = list(showgrid = TRUE,
                           gridcolor = toRGB("gray40"),
                           gridwidth = 0.5),
            lataxis = list(showgrid = TRUE,
                           gridcolor = toRGB("gray40"),
                           gridwidth = 0.5))

## add custom events
# dropdown
projections = data.frame(type = c("equirectangular", "mercator", "orthographic", "natural earth","kavrayskiy7", 
                                  "miller", "robinson", "eckert4", "azimuthal equal area","azimuthal equidistant", 
                                  "conic equal area", "conic conformal", "conic equidistant", "gnomonic",
                                  "stereographic","mollweide", "hammer", "transverse mercator", "albers usa",
                                  "winkel tripel"))

all_buttons <- list()
for (i in 1:length(projections[,])) { 
        all_buttons[[i]] <- list(method = "relayout",
                                 args = list(list(geo.projection.type = projections$type[i])),
                                 label = projections$type[i])
}

# sliders
lon_range = data.frame(x = seq(-180, 180, 10)) 
lat_range = data.frame(x = seq(-90, 90, 10))

all_lat <- list()
for (i in 1:length(lat_range[,])) { 
        all_lat[[i]] <- list(method = "relayout",
                             args = list(list(geo.projection.rotation.lat = lat_range$x[i])),
                             label = lat_range$x[i])
}

all_lon <- list()
for (i in 1:length(lon_range[,])) {  
        all_lon[[i]] <- list(method = "relayout", 
                             args = list(list(geo.projection.rotation.lon = lon_range$x[i])),
                             label = lon_range$x[i]) 
} 

# original d3-globe with contours
p<- plot_geo(df) %>% 
      group_by(line) %>% 
        add_lines(x = ~lon, 
                    y = ~lat, 
                      color = ~line, 
                        colors = 'Reds') %>% 
          layout(showlegend = FALSE, 
                   geo = geo) %>% 
          layout(annotations = list(x = 0, 
                                      y=0.8, 
                                        text = "Projection", 
                                          yanchor = 'bottom', 
                                            xref = 'paper', 
                                              xanchor = 'right',
                                                showarrow = FALSE),
                      updatemenus = list(list(active = 2, 
                                              x = 0, 
                                              y = 0.8, 
                                              buttons=all_buttons)),
                        sliders = list(list(active = (length(lon_range[,])-1)/2, 
                                            currentvalue = list(prefix = "Longitude: "), 
                                            pad = list(t = 20), 
                                            steps = all_lon),
                                       list(active = (length(lat_range[,])-1)/2, 
                                            currentvalue = list(prefix = "Latitude: "), 
                                            pad = list(t = 100),
                                            steps = all_lat)))
p

Animations

Frames

Ahora, junto con los datos y el diseño, se agregan frames a las claves que permite la figura. Los puntos clave de sus frame para una lista de figuras, cada una de las cuales se recorrerán en ciclo al crear una instancia del gráfico.

Mulitple Trace Animations

Cumulative Animations

Cumulative Lines Animation

Referencias

Plotly R Graphing Library | R | Plotly. (2020). Retrieved November 1, 2020, from https://plotly.com/r/