Chapter 9 Transforms
9.2 Group
9.2.1 Basic Example
library(plotly)
<- plot_ly(
fig type = 'scatter',
x = mtcars$hp,
y = mtcars$qsec,
text = paste("Make: ", rownames(mtcars),
"<br>hp: ", mtcars$hp,
"<br>qsec: ", mtcars$qsec,
"<br>Cyl: ", mtcars$cyl),
hoverinfo = 'text',
mode = 'markers',
transforms = list(
list(
type = 'groupby',
groups = mtcars$cyl,
styles = list(
list(target = 4, value = list(marker =list(color = 'blue'))),
list(target = 6, value = list(marker =list(color = 'red'))),
list(target = 8, value = list(marker =list(color = 'black')))
)
)
)
)
fig
9.3 Aggregation
9.3.1 Basic Example
library(plotly)
<- plot_ly(
fig 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
9.3.2 Histogram Binning
library(plotly)
<- read.csv("https://plotly.com/~public.health/17.csv", skipNul = TRUE, encoding = "UTF-8")
df
<- function(size, label) {
labels list(
args = c("xbins.size", size),
label = label,
method = "restyle"
)
}
<- df %>%
fig 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 %>% layout(
fig 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
9.3.3 Mapping with Aggregations
library(plotly)
<- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/worldhappiness.csv")
df
<- schema()
s <- s$transforms$aggregate$attributes$aggregations$items$aggregation$func$values
agg
= list()
l for (i in 1:length(agg)) {
= list(method = "restyle",
ll args = list('transforms[0].aggregations[0].func', agg[i]),
label = agg[i])
= ll
l[[i]]
}
<- df %>%
fig 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 %>% layout(
fig 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