Aggregations in R

How to use aggregates in R with Plotly.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.

Introduction

Aggregates are a type of transform that can be applied to values in a given expression. Available aggregations are:

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

library(plotly)

fig <- plot_ly(
  type = 'scatter',
  x = diamonds$cut,
  y = diamonds$price,
  mode = 'markers',
  transforms = list(
    list(
      type = 'aggregate',
      groups = diamonds$cut,
      aggregations = list(
        list(
          target = 'y', func = 'sum', enabled = T
        )
      )
    )
  )
)

fig
Click to copy

Aggregate Functions

library(plotly)
library(listviewer)

s <- schema()
agg <- s$transforms$aggregate$attributes$aggregations$items$aggregation$func$values


l = list()
for (i in 1:length(agg)) {
  ll = list(method = "restyle",
            args = list('transforms[0].aggregations[0].func', agg[i]),
            label = agg[i]) 
  l[[i]] = ll
}

fig <- plot_ly(
  type = 'scatter',
  x = diamonds$cut,
  y = diamonds$price,
  mode = 'markers',
  marker = list(
    size = 10,
    color = 'blue',
    opacity = 0.8
  ),
  transforms = list(
    list(
      type = 'aggregate',
      groups = diamonds$cut,
      aggregations = list(
        list(
          target = 'y', func = 'avg', enabled = T
        )
      )
    )
  )
)
fig <- fig %>% layout(
    title = '<b>Plotly Aggregations</b><br>use dropdown to change aggregation',
    xaxis = list(title = 'Cut'),
    yaxis = list(title = 'Price ($)'),
    updatemenus = list(
      list(
        x = 0.25,
        y = 1.04,
        xref = 'paper',
        yref = 'paper',
        yanchor = 'top',
        buttons = l
      )
    )
  )

fig
Click to copy
FairGoodVery GoodPremiumIdeal3400360038004000420044004600
Plotly Aggregationsuse dropdown to change aggregationCutPrice ($)count

Histogram Binning

library(plotly)

df <- read.csv("https://plotly.com/~public.health/17.csv", skipNul = TRUE, encoding = "UTF-8")

labels <- function(size, label) {
  list(
    args = c("xbins.size", size), 
    label = label, 
    method = "restyle"
  )
}

fig <- df %>%
  plot_ly(
    x = ~date,
    autobinx = FALSE, 
    autobiny = TRUE, 
    marker = list(color = "rgb(68, 68, 68)"), 
    name = "date", 
    type = "histogram", 
    xbins = list(
      end = "2016-12-31 12:00", 
      size = "M1", 
      start = "1983-12-31 12:00"
    )
  )
fig <- fig %>% layout(
  paper_bgcolor = "rgb(240, 240, 240)", 
  plot_bgcolor = "rgb(240, 240, 240)", 
  title = "<b>Shooting Incidents</b><br>use dropdown to change bin size",
  xaxis = list(
    type = 'date'
  ),
  yaxis = list(
    title = "Incidents"
  ),
  updatemenus = list(
    list(
      x = 0.1, 
      y = 1.15,
      active = 1, 
      showactive = TRUE,
      buttons = list(
        labels("D1", "Day"),
        labels("M1", "Month"),
        labels("M6", "Half Year"),
        labels("M12", "Year")
      )
    )
  )
)

fig
Click to copy
19851990199520002005201020150102030405060708090
Shooting Incidentsuse dropdown to change bin sizedateIncidentsMonth

Mapping with Aggregations

library(plotly)

df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/worldhappiness.csv")

s <- schema()
agg <- s$transforms$aggregate$attributes$aggregations$items$aggregation$func$values


l = list()
for (i in 1:length(agg)) {
  ll = list(method = "restyle",
            args = list('transforms[0].aggregations[0].func', agg[i]),
            label = agg[i]) 
  l[[i]] = ll
}

fig <- df %>%
  plot_ly(
    type = 'choropleth',
    locationmode = 'country names',
    locations = ~Country,
    z = ~HappinessScore,
    autocolorscale = F,
    reversescale = T,
    colorscale = 'Portland', 
    transforms = list(list(
      type = 'aggregate',
      groups = ~Country,
      aggregations = list(
        list(target = 'z', func = 'sum', enabled = T)
      )
    ))
  )
fig <- fig %>% layout(
    title = "<b>World Happiness</b>",
    geo = list(
      showframe = F,
      showcoastlines = F
    ),
    updatemenus = list(
      list(
        x = 0.25,
        y = 1.04,
        xref = 'paper',
        yref = 'paper',
        yanchor = 'top',
        buttons = l
      )
    )
  )

fig
Click to copy

Reference

See https://plotly.com/r/reference/ for more information and options!

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)
Click to copy