Los ejemplos son tomados de la página oficial de plotly, principalmente se obtienen algunos ejemplos gráficos con la estructura básica de plotly
.
Librerías
data <- read.csv("https://cdn.rawgit.com/plotly/datasets/master/GanttChart-updated.csv", stringsAsFactors = F) %>%
mutate(Start = as.Date(.$Start, format = "%m/%d/%Y")) %>%
mutate(color = factor(.$Resource,
labels = RColorBrewer::brewer.pal(length(unique(.$Resource)), name = "Set3")))
# Sample client name
client = "Sample Client"
# Initialize empty plot
p <- plot_ly()
# Each task is a separate trace
# Each trace is essentially a thick line plot
# x-axis ticks are dates and handled automatically
for(i in 1:(nrow(data) - 1)){
p <- add_trace(p,
x = c(data$Start[i], data$Start[i] + data$Duration[i]), # x0, x1
y = c(i, i), # y0, y1
mode = "lines",
line = list(color = data$color[i], width = 20),
showlegend = F,
hoverinfo = "text", # Create custom hover text
text = paste("Task: ", data$Task[i], "<br>",
"Duration: ", data$Duration[i], "days<br>",
"Resource: ", data$Resource[i]),
evaluate = T) # needed to avoid lazy loading
}
p
# Add information to plot and make the chart more presentable
# Axis options:
# 1. Remove gridlines
# 2. Customize y-axis tick labels and show task names instead of numbers
p <- layout(p,
xaxis = list(showgrid = F,
tickfont = list(color = "#05006E")),
yaxis = list(showgrid = F,
tickfont = list(color = "#05006E"),
tickmode = "array",
tickvals = 1:nrow(data),
ticktext = unique(data$Task),
domain = c(0, 0.9)),
plot_bgcolor = "#DBDBDB", # Chart area color
paper_bgcolor = "#DBDBDB") # Axis area color
p
# Add total duration and total resources used x and y coordinates are based on a domain of [0,1] and not
# actual x-axis and y-axis values
p <- p %>%
layout(annotations = list(xref = "paper",
yref = "paper",
x = 0.80,
y = 0.1,
text = paste0("Total Duration: ", sum(data$Duration), " days<br>",
"Total Resources: ", length(unique(data$Resource)), "<br>"),
font = list(color = '#264E86',
size = 20),
ax = 0,
ay = 0,
align = "left",
showarrow = FALSE)) %>%
layout(annotations = list(xref = "paper", # Add client name and title on top
yref = "paper",
x = 0.1,
y = 1,
xanchor = "left",
text = paste0("Gantt Chart: ", client),
font = list(color = '#264E86',
size = 40,
family = "Times New Roman"),
ax = 0,
ay = 0,
align = "left",
showarrow = FALSE))
p
Con branchvalues total
, representa el valor del padre que es el ancho de su cuña. En el siguiente ejemplo, Enoch
es 4 y Awan
es 6, por lo que el ancho de Enoch
es 4/6 de Awans
. Con branchvalues rest
, el ancho del padre está determinado por su propio valor más los de sus hijos. Entonces, el ancho de Enoch es 4/10 de Awan (4 / (6 + 4)).
Esto significa que la suma de los valores de los hijos no puede exceder el valor de su padre cuando los valores de rama son totals
. Cuando los valores de rama son “relativos” (el valor predeterminado), los niños no ocuparán todo el espacio debajo de su padre (a menos que el padre sea la raíz y tenga un valor de 0).
data <- data.frame(ids = c("North America", "Europe", "Australia", "North America - Football", "Soccer",
"North America - Rugby", "Europe - Football", "Rugby", "Europe - American Football",
"Australia - Football", "Association", "Australian Rules", "Autstralia - American Football",
"Australia - Rugby", "Rugby League", "Rugby Union"),
labels = c("North<br>America", "Europe", "Australia", "Football", "Soccer", "Rugby",
"Football", "Rugby", "American<br>Football", "Football", "Association",
"Australian<br>Rules", "American<br>Football", "Rugby", "Rugby<br>League",
"Rugby<br>Union"),
parents = c("", "", "", "North America", "North America", "North America", "Europe",
"Europe", "Europe","Australia", "Australia - Football", "Australia - Football",
"Australia - Football", "Australia - Football", "Australia - Rugby",
"Australia - Rugby"),
stringsAsFactors = FALSE)
p <- plot_ly(data,
ids = ~ids,
labels = ~labels,
parents = ~parents,
type = 'sunburst')
p
data1 <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/coffee-flavors.csv')
data2 <- read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
p <- plot_ly() %>%
add_trace(ids = data1$ids,
labels = data1$labels,
parents = data1$parents,
type = 'sunburst',
maxdepth = 2,
domain = list(column = 0)) %>%
add_trace(ids = data2$ids,
labels = data2$labels,
parents = data2$parents,
type = 'sunburst',
maxdepth = 3,
domain = list(column = 1)) %>%
layout(grid = list(columns =2, rows = 1),
margin = list(l = 0, r = 0, b = 0, t = 0),
sunburstcolorway = c("#636efa","#EF553B","#00cc96","#ab63fa","#19d3f3",
"#e763fa", "#FECB52","#FFA15A","#FF6692","#B6E880"),
extendsunburstcolors = TRUE)
p
p <- plot_ly(type = 'table',
columnwidth = c(100, 100),
columnorder = c(0, 1),
header = list(values = c("Cut","Price"),
align = c("center", "center"),
line = list(width = 1, color = 'black'),
fill = list(color = c("grey", "grey")),
font = list(family = "Arial", size = 14, color = "white")),
cells = list(values = rbind(diamonds$cut, diamonds$price),
align = c("center", "center"),
line = list(color = "black", width = 1),
font = list(family = "Arial", size = 12, color = c("black"))))
p
p <- plot_ly(type = 'table',
header = list(values = c('<b>EXPENSES</b>', '<b>Q1</b>','<b>Q2</b>','<b>Q3</b>','<b>Q4</b>'),
line = list(color = '#506784'),
fill = list(color = '#119DFF'),
align = c('left','center'),
font = list(color = 'white', size = 12)),
cells = list(values = rbind(c('Salaries', 'Office', 'Merchandise', 'Legal', '<b>TOTAL</b>'),
c(1200000, 20000, 80000, 2000, 1212000),
c(1300000, 20000, 70000, 2000, 1392000),
c(1300000, 20000, 120000, 2000, 1442000),
c(1400000, 20000, 90000, 2000, 1412000)),
line = list(color = '#506784'),
fill = list(color = c('#25FEFD', 'white')),
align = c('left', 'center'),
font = list(color = c('#506784'), size = 12)))
p
p <- plot_ly(type = 'table',
header = list(values = c("<b>Cars</b>", names(mtcars)),
align = c('left', rep('center', ncol(mtcars))),
line = list(width = 1, color = 'black'),
fill = list(color = 'rgb(235, 100, 230)'),
font = list(family = "Arial", size = 14, color = "white")),
cells = list(values = rbind(rownames(mtcars), t(as.matrix(unname(mtcars)))),
align = c('left', rep('center', ncol(mtcars))),
line = list(color = "black", width = 1),
fill = list(color = c('rgb(235, 193, 238)', 'rgba(228, 222, 249, 0.65)')),
font = list(family = "Arial", size = 12, color = c("black"))))
p
values <- rbind(c('Salaries', 'Office', 'Merchandise', 'Legal', '<b>TOTAL<br>EXPENSES</b>'),
c("Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad",
"Lorem ipsum dolor sit amet, tollit discere inermis pri ut. Eos ea iusto timeam, an prima laboramus vim. Id usu aeterno adversarium, summo mollis timeam vel ad"))
p <- plot_ly(type = 'table',
columnorder = c(1,2),
columnwidth = c(80,400),
header = list(values = c('<b>EXPENSES</b><br>as of July 2017', '<b>DESCRIPTION</b>'),
line = list(color = '#506784'),
fill = list(color = '#119DFF'),
align = c('left','center'),
font = list(color = 'white', size = 12),
height = 40),
cells = list(values = values,
line = list(color = '#506784'),
fill = list(color = c('#25FEFD', 'white')),
align = c('left', 'center'),
font = list(color = c('#506784'), size = 12),
height = 30))
p
p <- plot_ly(type = "sankey",
orientation = "h",
node = list(label = c("A1", "A2", "B1", "B2", "C1", "C2"),
color = c("blue", "blue", "blue", "blue", "blue", "blue"),
pad = 15,
thickness = 20,
line = list(color = "black", width = 0.5)),
link = list(source = c(0,1,0,2,3,3),
target = c(2,3,3,4,4,5),
value = c(8,4,2,8,4,2))) %>%
layout(title = "Basic Sankey Diagram",
font = list(size = 10))
p
p <- plot_ly(type = "sankey",
domain = list(x = c(0,1),
y = c(0,1)),
orientation = "h",
valueformat = ".0f",
valuesuffix = "TWh") %>%
layout(title = "Energy forecast for 2050, UK - Department of Energy & Climate Change",
font = list(size = 10),
xaxis = list(showgrid = F,
zeroline = F),
yaxis = list(showgrid = F,
zeroline = F))
json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))
p <- plot_ly(type = "sankey",
domain = list(x = c(0,1),
y = c(0,1)),
orientation = "h",
valueformat = ".0f",
valuesuffix = "TWh",
node = list(label = json_data$data[[1]]$node$label,
color = json_data$data[[1]]$node$color,
pad = 15,
thickness = 15,
line = list(color = "black", width = 0.5))) %>%
layout(title = "Energy forecast for 2050, UK - Department of Energy & Climate Change",
font = list(size = 10),
xaxis = list(showgrid = F, zeroline = F),
yaxis = list(showgrid = F, zeroline = F))
json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))
p <- plot_ly(type = "sankey",
domain = list(x = c(0,1),
y = c(0,1)),
orientation = "h",
valueformat = ".0f",
valuesuffix = "TWh",
node = list(label = json_data$data[[1]]$node$label,
color = json_data$data[[1]]$node$color,
pad = 15,
thickness = 15,
line = list(color = "black", width = 0.5)),
link = list(source = json_data$data[[1]]$link$source,
target = json_data$data[[1]]$link$target,
value = json_data$data[[1]]$link$value,
label = json_data$data[[1]]$link$label)) %>%
layout(title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>",
font = list(size = 10),
xaxis = list(showgrid = F, zeroline = F),
yaxis = list(showgrid = F, zeroline = F))
p
json_file <- "https://raw.githubusercontent.com/plotly/plotly.js/master/test/image/mocks/sankey_energy.json"
json_data <- fromJSON(paste(readLines(json_file), collapse=""))
p <- plot_ly(type = "sankey",
domain = list(x = c(0,1),
y = c(0,1)),
orientation = "h",
valueformat = ".0f",
valuesuffix = "TWh",
node = list(label = json_data$data[[1]]$node$label,
color = json_data$data[[1]]$node$color,
pad = 15,
thickness = 15,
line = list(color = "black", width = 0.5)),
link = list(source = json_data$data[[1]]$link$source,
target = json_data$data[[1]]$link$target,
value = json_data$data[[1]]$link$value,
label = json_data$data[[1]]$link$label)) %>%
layout(title = "Energy forecast for 2050<br>Source: Department of Energy & Climate Change, Tom Counsell via <a href='https://bost.ocks.org/mike/sankey/'>Mike Bostock</a>",
font = list(size = 10, color = 'white'),
xaxis = list(showgrid = F,
zeroline = F,
showticklabels = F),
yaxis = list(showgrid = F,
zeroline = F,
showticklabels = F),
plot_bgcolor = 'black',
paper_bgcolor = 'black')
p
El siguiente ejemplo establece node.x
y node.y
para colocar nodos en las ubicaciones especificadas, excepto en la disposición de ajuste (comportamiento predeterminado cuando node.x
y node.y
no están definidos) para evitar la superposición de los nodos, por lo tanto, el ajuste de elementos se establecerá para definir el relleno entre nodos a través de nodepad. Las otras disposiciones posibles son: 1) perpendicular
2) freeform
3) fixed
p <- plot_ly(type = "sankey",
arrangement = "snap",
node = list(label = c("A", "B", "C", "D", "E", "F"),
x = c(0.2, 0.1, 0.5, 0.7, 0.3, 0.5),
y = c(0.7, 0.5, 0.2, 0.4, 0.2, 0.3),
pad = 10), # 10 Pixel
link = list(source = c(0, 0, 1, 2, 5, 4, 3, 5),
target = c(5, 3, 4, 3, 0, 2, 2, 3),
value = c(1, 2, 1, 1, 1, 1, 1, 2))) %>%
layout(title = "Sankey with manually positioned node")
p
Los treemap que son creados en plotly
son interactivos de forma predeterminada. Se hace clic en los sectores individuales del gráfico de mapa de árbol para acercar o alejar ese sector y mostrar una barra de ruta jerárquica en la parte superior del gráfico. Se puede utilizar esta barra de ruta para acercar o alejar los sectores del gráfico en lugar de hacer clic en los sectores directamente.
Puede personalizar varios atributos de los mapas de árbol que crea con plotly, que incluyen:
values
: una lista de los valores asignados a cada sector del gráfico.
textinfo
: determina la información textual que aparecerá en cada sector del gráfico. Los valores válidos son texto, value, current path, percent root, percent entry, percent parent o cualquier combinación de los anteriores.
pathbar
: determina si la barra de ruta es visible cuando los usuarios hacen zoom en los sectores del gráfico.
branchvalues
: el método que se ha utilizado para calcular los valores de los sectores del gráfico que tienen desendants
. Los valores válidos para este atributo son total
y remainder
; el valor predeterminado es el remainder
.
Cuando se configura como remainder
, los elementos del atributo de valores que corresponden a la raíz y los sectores de ramas se toman como la parte extra, no como parte de la suma de los valores en sus hojas.
data <- data.frame(labels = c("Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"),
parents = c("", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve"))
p <- plot_ly(data,
type ='treemap',
labels = ~labels,
parents = ~parents,
values = c(10, 14, 12, 10, 2, 6, 6, 1, 4),
textinfo = "label+value+percent parent+percent entry+percent root",
domain = list(column=0)) %>%
add_trace(type ='treemap',
branchvalues ="total",
labels = ~labels,
parents = ~parents,
values = c(65, 14, 12, 10, 2, 6, 6, 1, 4),
textinfo = "label+value+percent parent+percent entry",
outsidetextfont = list(size=20, color= "darkblue"),
marker=list(line = list(width=2)),
pathbar = list(visible = FALSE),
domain = list(column = 1)) %>%
layout(grid = list(columns = 2, rows = 1),
margin=list(l=0, r=0, b=0, t=0))
p
Existen tres atributos diferentes que puede usar para cambiar el color de los sectores de los mapas de árbol:
Los siguientes ejemplos muestran cómo utilizar cada atributo. Para usar marker.colors
, pase una lista de colores CSS válidos o códigos de colores hexadecimales.
data <- data.frame(labels = c("A1", "A2", "A3", "A4", "A5", "B1", "B2"),
parents = c("", "A1", "A2", "A3", "A4", "", "B1"))
p <- plot_ly(data,
type="treemap",
labels = ~labels,
parents = ~parents,
marker=list(colors=c("#000", "royalblue", "lightgray", "purple", "#FFF",
"lightgray", "lightblue")))
p
El siguiente ejemplo utiliza el atributo marker.colorscale
. En lugar de utilizar una lista de colores, simplemente proporcione una escala de colores.
Las escalas de colores integradas son: Greys, YlGnBu, Greens, YlOrRd, Bluered, RdBu, Reds, Blue, Picnic, Rainbow, Portland, Jet, Hot, Blackbody, Earth, Electric, Viridis y Cividis.
data <- data.frame(labels = c("A1", "A2", "A3", "A4", "A5", "B1", "B2"),
parents = c("", "A1", "A2", "A3", "A4", "", "B1"),
values = c("11", "12", "13", "14", "15", "20", "30"))
p <- plot_ly(data,
type = "treemap",
labels = ~labels,
parents = ~parents,
values = ~values,
marker=list(colorscale='Reds'))
p
El siguiente ejemplo utiliza el atributo treemapcolorway
, que debe establecerse en el diseño del gráfico.
El siguiente ejemplo demuestra cómo se pueden usar los gráficos de mapas de árbol para revelar información sobre la estructura de los datos jerárquicos que incluyen información sobre capas y agrupaciones. El atributo maxdepth
se puede utilizar para controlar cuántos niveles de datos se representan; el valor predeterminado de -1 representa todos los niveles de la jerarquía.
df1 = read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')
df2 = read.csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/coffee-flavors.csv')
p <- plot_ly(type='treemap',
ids=df1$ids,
labels=df1$labels,
parents=df1$parents,
domain=list(column=0)) %>%
add_trace(type='treemap',
ids=df2$ids,
labels=df2$labels,
parents=df2$parents,
maxdepth=1,
domain=list(column=1)) %>%
layout(grid=list(columns=2, rows=1))
p
uniformtext
De forma predeterminada, el tamaño de fuente de las etiquetas de texto en su gráfico de mapa de árbol variará para adaptarse al espacio disponible dentro de un sector. Sin embargo, si desea que todas las etiquetas de texto en el gráfico de mapa de árbol tengan el mismo tamaño de fuente, puede usar el parámetro uniformtext
. El atributo minsize
establece el tamaño de la fuente y el atributo mode
establece lo que sucede con las etiquetas que no pueden caber dentro de un sector con el tamaño de fuente especificado: hide
o show
.
Los gráficos de embudo se utilizan a menudo para representar datos en diferentes etapas de un proceso empresarial. Es un mecanismo importante en Business Intelligence para identificar posibles áreas problemáticas de un proceso. Por ejemplo, se utiliza para observar los ingresos o pérdidas en un proceso de ventas para cada etapa y muestra valores que disminuyen progresivamente.
p <- plot_ly() %>%
add_trace(type = "funnel",
y = c("Website visit", "Downloads", "Potential customers", "Requested price",
"invoice sent"),
x = c(39, 27.4, 20.6, 11, 2)) %>%
layout(yaxis = list(categoryarray = c("Website visit", "Downloads", "Potential customers",
"Requested price", "invoice sent")))
p
p <- plot_ly() %>%
add_trace(type = "funnel",
y = c("Website visit", "Downloads", "Potential customers", "Requested price",
"Finalized"),
x = c(39, 27.4, 20.6, 11, 2),
textposition = "inside",
textinfo = "value+percent initial",
opacity = 0.65,
marker = list(color = c("deepskyblue", "lightsalmon", "tan", "teal", "silver"),
line = list(width = c(4, 2, 2, 3, 1, 1),
color = c("wheat", "wheat", "blue", "wheat", "wheat"))),
connector = list(line = list(color = "royalblue",
dash = "dot",
width = 3))) %>%
layout(yaxis = list(categoryarray = c("Website visit", "Downloads", "Potential customers",
"Requested price", "Finalized")))
p
p <- plot_ly(type = "funnel",
name = 'Montreal',
y = c("Website visit", "Downloads", "Potential customers", "Requested price"),
x = c(120, 60, 30, 20),
textinfo = "value+percent initial") %>%
add_trace(type = "funnel",
name = 'Toronto',
orientation = "h",
y = c("Website visit", "Downloads", "Potential customers", "Requested price", "invoice sent"),
x = c(100, 60, 40, 30, 20),
textposition = "inside",
textinfo = "value+percent previous") %>%
add_trace(type = "funnel",
name = 'Vancouver',
orientation = "h",
y = c("Website visit", "Downloads", "Potential customers", "Requested price",
"invoice sent", "Finalized"),
x = c(90, 70, 50, 30, 10, 5),
textposition = "outside",
textinfo = "value+percent total") %>%
layout(yaxis = list(categoryarray = c("Website visit", "Downloads", "Potential customers",
"Requested price", "invoice sent", "Finalized")))
p
p <- plot_ly(type = "funnelarea",
values = c(5, 4, 3, 2, 1),
text = c("The 1st","The 2nd", "The 3rd", "The 4th", "The 5th"),
marker = list(colors = c("deepskyblue", "lightsalmon", "tan", "teal", "silver"),
line = list(color = c("wheat", "wheat", "blue", "wheat", "wheat"),
width = c(0, 1, 5, 0, 4))),
textfont = list(family = "Old Standard TT, serif",
size = 13,
color = "black"),
opacity = 0.65)
p
p <- plot_ly(type = "funnelarea",
scalegroup = "first",
values = c(500, 450, 340, 230, 220, 110),
textinfo = "value",
title = list(position = "top center",
text = "Sales for Sale Person A in U.S."),
domain = list(x = c(0.01, 0.48),
y =c(0, 0.5))) %>%
add_trace(type = "funnelarea",
scalegroup = "first",
values = c(600, 500, 400, 300, 200, 100),
textinfo = "value",
title = list(position = "top center",
text = "Sales of Sale Person B in Canada"),
domain = list(x = c(0.01, 0.48),
y = c(0.56, 1))) %>%
add_trace(type = "funnelarea",
scalegroup = "second",
values = c(510, 480, 440, 330, 220, 100),
textinfo = "value",
title = list(position = "top left",
text = "Sales of Sale Person A in Canada"),
domain = list(x = c(0.56, 0.98),
y = c(0, 0.5))) %>%
add_trace(type = "funnelarea",
scalegroup = "second",
values = c(360, 250, 240, 130, 120, 60),
textinfo = "value",
title = list(position = "top left",
text = "Sales of Sale Person B in U.S."),
domain = list(x = c(0.56, 0.98),
y = c(0.56, 1))) %>%
layout(margin = list(l= 200, r= 200),
shapes = list(list(x0 = 0, x1 = 0.5, y0 = 0, y1 = 0.5),
list(x0 = 0, x1 = 0.5, y0 = 0.55, y1 = 1),
list(x0 = 0.55, x1 = 1, y0 = 0, y1 = 0.5),
list(x0 = 0.55, x1 = 1, y0 = 0.55, y1 = 1)))
p
Un gráfico de calibre radial tiene un arco circular, que muestra un valor único para estimar el progreso hacia una meta. La barra muestra el valor objetivo y el sombreado representa el progreso hacia ese objetivo. Gráficos de calibre, también conocidos como gráficos de velocímetro. Este tipo de gráfico se usa generalmente para ilustrar indicadores comerciales clave.
Los siguientes ejemplos incluyen el atributo steps
que se muestra como sombreado dentro del arco radial, delta
que es la diferencia del valor y el objetivo (referencia - valor) y threshold
para determinar los límites que le avisan visualmente si el valor cruza un umbral definido.
p <- plot_ly(domain = list(x = c(0, 1), y = c(0, 1)),
value = 450,
title = list(text = "Speed"),
type = "indicator",
mode = "gauge+number+delta",
delta = list(reference = 380),
gauge = list(axis =list(range = list(NULL, 500)),
steps = list(list(range = c(0, 250), color = "lightgray"),
list(range = c(250, 400), color = "gray")),
threshold = list(line = list(color = "red", width = 4),
thickness = 0.75,
value = 490))) %>%
layout(margin = list(l=20,r=30))
p
p <- plot_ly(type = "indicator",
mode = "gauge+number+delta",
value = 420,
title = list(text = "Speed", font = list(size = 24)),
delta = list(reference = 400,
increasing = list(color = "RebeccaPurple")),
gauge = list(axis = list(range = list(NULL, 500),
tickwidth = 1,
tickcolor = "darkblue"),
bar = list(color = "darkblue"),
bgcolor = "white",
borderwidth = 2,
bordercolor = "gray",
steps = list(list(range = c(0, 250), color = "cyan"),
list(range = c(250, 400), color = "royalblue")),
threshold = list(line = list(color = "red", width = 4),
thickness = 0.75,
value = 490))) %>%
layout(margin = list(l=20,r=30),
paper_bgcolor = "lavender",
font = list(color = "darkblue", family = "Arial"))
p
data <- data.frame(x = c("Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax"),
measure = c("relative", "relative", "total", "relative", "relative", "total"),
text = c("+60", "+80", "", "-40", "-20", "Total"),
y = c(60, 80, 0, -40, -20, 0)) %>%
mutate(x = factor(.$x, levels = .$x))
p <- plot_ly(data,
name = "20",
type = "waterfall",
measure = ~measure,
x = ~x,
textposition = "outside",
y= ~y,
text =~text,
connector = list(line = list(color= "rgb(63, 63, 63)"))) %>%
layout(title = "Profit and loss statement 2018",
xaxis = list(title = ""),
yaxis = list(title = ""),
autosize = TRUE,
showlegend = TRUE)
p
Este ejemplo usa atributos decrecientes, crecientes y totales para personalizar las barras.
data <- data.frame(y = c(375, 128, 78, 0, -327, -78, 0, 32, 89, 0, -45, 0),
x = c("Sales", "Consulting", "Maintenance", "Net revenue", "Purchases", "Material expenses", "Operating profit", "Investment income", "Financial income", "Profit before tax", "Income tax (15%)", "Profit after tax"),
measure = c("relative", "relative", "relative", "total", "relative", "relative", "total", "relative", "relative", "total", "relative", "total")) %>%
mutate(x = factor(.$x, levels = .$x))
p <- plot_ly(data,
x = ~x,
y = ~y,
measure = ~measure,
type = "waterfall",
base = 300,
decreasing = list(marker = list(color = "Maroon",
line = list(color = "red", width = 2))),
increasing = (marker = list(color = "Teal")),
totals = list(marker = list(color = "deep sky blue",
line = list(color = 'blue', width = 3)))) %>%
layout(title = "Profit and loss statement",
xaxis = list(title = "", tickfont = "16", ticks = "outside"),
yaxis = list(title = ""), waterfallgap = "0.3")
p
data <- data.frame(x = c(375, 128, 78, 27, 0, -327, -12, -78, -12, 0, 32, 89, 0, -45, 0),
y = c("Sales", "Consulting", "Maintenance", "Other revenue", "Net revenue", "Purchases",
"Material expenses", "Personnel expenses", "Other expenses", "Operating profit",
"Investment income", "Financial income", "Profit before tax", "Income tax (15%)", "Profit after tax"),
measure = c("relative", "relative", "relative", "relative", "total", "relative", "relative",
"relative", "relative", "total", "relative", "relative", "total", "relative", "total")) %>%
mutate(y = factor(.$y, levels = .$y))
p <- plot_ly(data,
x = ~x,
y = ~y,
measure = ~measure,
type = "waterfall",
name = "2018",
orientation = "h",
connector = list(mode = "between",
line = list(width = 4, color = "rgb(0, 0, 0)", dash = 0))) %>%
layout(title = "Profit and loss statement 2018<br>waterfall chart displaying positive and negative",
xaxis = list(title = "",
tickfont = "16",
ticks = "outside",
type = "linear"),
yaxis = list(title = "",
type = "category",
autorange = "reversed"),
margin = c(l = 150),
showlegend = TRUE)
p
El Bullet Chart de Stephen Few
se inventó para reemplazar los medidores y medidores del tablero, combinando ambos tipos de gráficos en gráficos de barras simples con barras cualitativas (steps), barra cuantitativa (bars) y línea de rendimiento (threshold); todo en un diseño simple. Los pasos generalmente se dividen en varios valores, que se definen con una matriz. La barra representa el valor real que alcanzó una variable en particular, y el umbral generalmente indica un punto de meta relativo al valor alcanzado por la barra.
p <- plot_ly(type = "indicator",
mode = "number+gauge+delta",
gauge = list(shape = "bullet"),
delta = list(reference = 300),
value = 220,
domain = list(x = c(0, 1), y = c(0, 1)),
title= list(text = "Profit"),
height = 150)
p
A continuación se muestra el mismo ejemplo que utiliza el atributo steps
, que se muestra como sombreado, y threshold
para determinar los límites que le alertan visualmente si el valor cruza un umbral definido.
p <- plot_ly(type = "indicator",
mode = "number+gauge+delta",
value = 220,
domain = list(x = c(0, 1), y= c(0, 1)),
title = list(text = "<b>Profit</b>"),
delta = list(reference = 200),
gauge = list(shape = "bullet",
axis = list(range = list(NULL, 300)),
threshold = list(line = list(color = "red", width = 2),
thickness = 0.75,
value = 280),
steps = list(list(range = c(0, 150), color = "lightgray"),
list(range = c(150, 250), color = "gray"))),
height = 150, width = 600) %>%
layout(margin = list(l= 100, r= 10))
p
p <- plot_ly(type = "indicator",
mode = "number+gauge+delta",
value = 220,
domain = list(x = c(0, 1), y = c(0, 1)),
delta = list(reference = 280, position = "top"),
title = list(text = "<b>Profit</b><br><span style='color: gray; font-size:0.8em'>U.S. $</span>",
font = list(size = 14)),
gauge = list(shape = "bullet",
axis = list(range = c(NULL, 300)),
threshold = list(line = list(color = "red",
width = 2,
gradient = list(yanchor = "vertical")),
thickness = 0.75,
value = 270),
bgcolor = "white",
steps = list(list(range = c(0, 150), color = "cyan")),
bar = list(color = "darkblue")),
height = 150)
p
p <- plot_ly() %>%
add_trace(type = "indicator",
mode = "number+gauge+delta",
value = 180,
delta = list(reference = 200),
domain = list(x = c(0.25, 1), y = c(0.08, 0.25)),
title =list(text = "Revenue"),
gauge = list(shape = "bullet",
axis = list(range = c(NULL, 300)),
threshold = list(line= list(color = "black", width = 2),
thickness = 0.75,
value = 170),
steps = list(list(range = c(0, 150), color = "gray"),
list(range = c(150, 250), color = "lightgray")),
bar = list(color = "black"))) %>%
add_trace(type = "indicator",
mode = "number+gauge+delta",
value = 35,
delta = list(reference = 200),
domain = list(x = c(0.25, 1), y = c(0.4, 0.6)),
title = list(text = "Profit"),
gauge = list(shape = "bullet",
axis = list(range = list(NULL, 100)),
threshold = list(line = list(color = "black", width= 2),
thickness = 0.75,
value = 50),
steps = list(list(range = c(0, 25), color = "gray"),
list(range = c(25, 75), color = "lightgray")),
bar = list(color = "black"))) %>%
add_trace(type = "indicator",
mode = "number+gauge+delta",
value = 220,
delta = list(reference = 300 ),
domain = list(x = c(0.25, 1), y = c(0.7, 0.9)),
title = list(text = "Satisfaction"),
gauge = list(shape = "bullet",
axis = list(range = list(NULL, 300)),
threshold = list(line = list(color = "black", width = 2),
thickness = 0.75,
value = 210),
steps = list(list(range = c(0, 100), color = "gray"),
list(range = c(100, 250), color = "lightgray")),
bar = list(color = "black")))
p
El atributo rangebreaks
disponible en los ejes \(x\) e \(y\) de tipo fecha se puede utilizar para ocultar ciertos períodos de tiempo. En el siguiente ejemplo, se muestran dos gráficos: uno en modo predeterminado para mostrar brechas en los datos y otro en el que ocultamos fines de semana y días festivos para mostrar un historial comercial ininterrumpido. Los espacios más pequeños entre las líneas de la cuadrícula para el 21 de diciembre y el 4 de enero, donde se eliminaron las vacaciones.
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
p <- plot_ly(type = "scatter",
x = as.Date(df$Date, format= "%Y-%m-%d"),
y = df$AAPL.High,
name = 'AAPL High',
mode = "markers")%>%
layout(title = "Time Series with Custom Date-Time Format",
xaxis = list(type = "date",
range=c('2015-12-01', '2016-01-15')))
p
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
p <- plot_ly(type = "scatter",
x = as.Date(df$Date, format= "%Y-%m-%d"),
y = df$AAPL.High,
name = 'AAPL High',
mode = "markers+lines") %>%
layout(title = "Time Series with Custom Date-Time Format",
xaxis = list(type = "date",
range=c('2015-12-01', '2016-01-15'),
rangebreaks = list(list(bounds=c("sat", "mon")),
list(values=c("2015-12-25", "2016-01-01")))))
p
## [1] "AAPL"
df <- data.frame(Date=index(AAPL),coredata(AAPL))
p <- df %>%
plot_ly(x = ~Date,
type="candlestick",
open = ~AAPL.Open,
close = ~AAPL.Close,
high = ~AAPL.High,
low = ~AAPL.Low) %>%
layout(title = "Apple Stock",
annotations = list(text = "Stock Split",
x = '2014-06-06',
y = 1.02,
xref = 'x',
yref = 'paper',
xanchor = 'left',
showarrow = FALSE),
shapes = list(type = line, # use shapes to create a line
x0 = '2014-06-06',
x1 = '2014-06-06',
y0 = 0,
y1 = 1,
xref = 'x',
yref = 'paper',
line = list(color = 'black',
width = 0.5)))
p
df <- data.frame(Date=index(AAPL),coredata(AAPL)) %>%
tail(365)
p <- df %>%
plot_ly(x = ~Date,
type="candlestick",
open = ~AAPL.Open,
close = ~AAPL.Close,
high = ~AAPL.High,
low = ~AAPL.Low) %>%
add_lines(x = ~Date,
y = ~AAPL.Open,
line = list(color = 'black', width = 0.75),
inherit = F) %>%
layout(showlegend = FALSE)
p
msft <- getSymbols("MSFT", auto.assign = F)
data<-as.data.frame(msft) %>%
mutate(date = index(msft)) %>%
filter(.$date >="2016-01-01")
names(data) <- sub("^MSFT\\.", "", names(data))
p <- plot_ly(data,
x = ~date,
xend = ~date,
color = ~Close > Open,
colors = c("red", "forestgreen"),
hoverinfo = "none") %>%
add_segments(y = ~Low,
yend = ~High,
size = I(1)) %>%
add_segments(y = ~Open,
yend = ~Close,
size = I(3)) %>%
layout(showlegend = FALSE,
yaxis = list(title = "Price")) %>%
rangeslider()
p
## [1] "AAPL"
data <- data.frame(Date=index(AAPL),coredata(AAPL))
p <- data %>%
plot_ly(x = ~Date,
type="ohlc",
open = ~AAPL.Open,
close = ~AAPL.Close,
high = ~AAPL.High,
low = ~AAPL.Low) %>%
layout(title = "Custom Colors",
annotations = list(text = "Stock Split",
x = '2014-06-06',
y = 1.02,
xref = 'x',
yref = 'paper',
xanchor = 'left',
showarrow = FALSE),
shapes = list(type = line, # use shapes to create a line
x0 = '2014-06-06',
x1 = '2014-06-06',
y0 = 0,
y1 = 1,
xref = 'x',
yref = 'paper',
line = list(color = 'black',width = 0.5)))
p
Plotly R Graphing Library | R | Plotly. (n.d.). Retrieved August 5, 2020, from https://plotly.com/r/