Los ejemplos son tomados de la página oficial de plotly, principalmente se obtienen algunos ejemplos gráficos de plotly.
Librerías
\[\text{Filter }\rightarrow y_{hp}>\bar{x_{qsec}}\]
p <- plot_ly(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')))))))
p| 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. |
require(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
}
p <- 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))))) %>%
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)))
pdf <- 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")
}
p <- 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")) %>%
layout(title = "<b>Shooting Incidents</b><br>use dropdown to change bin size",
paper_bgcolor = "rgb(240, 240, 240)",
plot_bgcolor = "rgb(240, 240, 240)",
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")))))
pdf <- 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
}
p <- 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', #HappinessScore
func = 'sum',
enabled = T))))) %>% 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)))
pdf <- data.frame(x = c("1", "2", "3", "4", "5"),
y = c("1", "1", "1", "1", "1"))
# create steps for slider
steps <- list(list(args = list("marker.color", "red"),
label = "Red",
method = "restyle",
value = "1"),
list(args = list("marker.color", "green"),
label = "Green",
method = "restyle",
value = "2"),
list(args = list("marker.color", "blue"),
label = "Blue",
method = "restyle",
value = "3"))
p<- df %>%
plot_ly(x = ~x,
y = ~y,
mode = "markers",
marker = list(size = 20,
color = 'green'),
type = "scatter") %>%
layout(title = "Basic Slider",
sliders = list(list(active = 1,
currentvalue = list(prefix = "Color: "),
pad = list(t = 60),
steps = steps)))
px <- seq(0,10, length.out = 1000)
# create data
aval <- list()
for(step in 1:11){
aval[[step]] <-list(visible = FALSE,
name = paste0('v = ', step),
x = x,
y = sin(step*x))
}
aval[3][[1]]$visible = TRUE
# create steps and plot all traces
steps <- list()
p <- plot_ly()
for (i in 1:11) {
p <- add_lines(p,
x=aval[i][[1]]$x,
y=aval[i][[1]]$y,
visible = aval[i][[1]]$visible,
name = aval[i][[1]]$name,
type = 'scatter',
mode = 'lines',
hoverinfo = 'name',
line=list(color='00CED1'),
showlegend = FALSE)
step <- list(args = list('visible', rep(FALSE, length(aval))),
method = 'restyle')
step$args[[2]][i] = TRUE
steps[[i]] = step
}
# add slider control to plot
p <- p %>%
layout(sliders = list(list(active = 3,
currentvalue = list(prefix = "Frequency: "),
steps = steps)))
pdf <- 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)))
pAhora, 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.
require(ggplot2)
accumulate_by <- function(dat, var) {
var <- lazyeval::f_eval(var, dat)
lvls <- plotly:::getLevels(var)
dats <- lapply(seq_along(lvls), function(x) {
cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})
dplyr::bind_rows(dats)
}
df <- ggplot2::txhousing
p <- df %>%
filter(year > 2005, city %in% c("Abilene", "Bay Area")) %>%
accumulate_by(~date) %>%
plot_ly(x = ~date,
y = ~median,
split = ~city,
frame = ~frame,
type = 'scatter',
mode = 'lines',
line = list(simplyfy = F)) %>%
layout(xaxis = list(title = "Date",
zeroline = F),
yaxis = list(title = "Median",
zeroline = F)) %>%
animation_opts(frame = 100,
transition = 0,
redraw = FALSE) %>%
animation_slider(hide = T) %>%
animation_button(x = 1,
xanchor = "right",
y = 0,
yanchor = "bottom")
pPlotly R Graphing Library | R | Plotly. (2020). Retrieved November 1, 2020, from https://plotly.com/r/