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.
La función ggplotly() debe respetar ciertos criterios de ggplot, como texto (Para personalizar la información sobre los gráficos), frame (para crear animaciones ) e ID’s (para garantizar transiciones suaves y sensibles). Dado que ggplotly() del paquete ggplot2 devuelve un objeto qué se puede aplicar esencialmente a cualquier función del paquete R.
Existen algunos argumentos como:
\(\bullet\) layout() que sirve para personalizar el diseño del gráfico.
\(\bullet\) add_traces() y toda la estructura add_**(), por ejemplo add_polygons(), que sirven para agregar nuevos datos o gráficos.
\(\bullet\) subplot() para combinar múltiples objetos plotly.
\(\bullet\) Plotly_json() para inspeccionar el JSON subyacente enviado a plotly.js.
La función plot_ly () proporciona una interfaz más directa a plotly.js para que pueda aprovechar tipos de gráficos más especializados (por ejemplo, parallel coordinates o mapas) o incluso alguna visualización que la API en ggplot2 nunca admitirá (por ejemplo, surface, mesh, trisurf, etc.)
Este cheatsheet provee un resumen de los tipos de gráficos que están disponible en plotly.
Librerías
require(plotly)
require(knitr)
require(tidyr)
require(dplyr)
require(mvtnorm)
require(stringr)
require(reshape2)data<- data.frame(trace_0 = rnorm(100, mean = 5),
trace_1 = rnorm(100, mean = 0),
trace_2 = rnorm(100, mean = -5),
x = c(1:100))
p <- plot_ly(data, x = ~x ) %>%
add_trace(y = ~trace_0,
name = 'trace 0',
mode = 'lines',
line=list(color=c("#581845"))) %>%
add_trace(y = ~trace_1,
name = 'trace 1',
mode = 'lines+markers',
marker=list(color=c("#C70039")),
line=list(color=c("#C70039"))) %>%
add_trace(y = ~trace_2,
name = 'trace 2',
mode = 'markers',
marker=list(color=c("#FF5733"))) %>%
layout(yaxis=list(title=""))
pdata<- data.frame(month = c('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'),
high_2000 = c(32.5, 37.6, 49.9, 53.0, 69.1, 75.4, 76.5, 76.6, 70.7, 60.6, 45.1, 29.3),
low_2000 = c(13.8, 22.3, 32.5, 37.2, 49.9, 56.1, 57.7, 58.3, 51.2, 42.8, 31.6, 15.9),
high_2007 = c(36.5, 26.6, 43.6, 52.3, 71.5, 81.4, 80.5, 82.2, 76.0, 67.3, 46.1, 35.0),
low_2007 = c(23.6, 14.0, 27.0, 36.8, 47.6, 57.7, 58.9, 61.2, 53.3, 48.5, 31.0, 23.6),
high_2014 = c(28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9),
low_2014 = c(12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1)) %>%
mutate(month = factor(.$month,levels=.$month))
p <- plot_ly(data,
x = ~month,
y = ~high_2014,
name = 'High 2014',
type = 'scatter',
mode = 'lines',
line = list(color = 'rgb(199, 0, 57)', width = 4)) %>%
add_trace(y = ~low_2014,
name = 'Low 2014',
line = list(color = 'rgb(59, 82, 128)', width = 4)) %>%
add_trace(y = ~high_2007,
name = 'High 2007',
line = list(color = 'rgb(199, 0, 57)', width = 4, dash = 'dash')) %>%
add_trace(y = ~low_2007,
name = 'Low 2007',
line = list(color = 'rgb(59, 82, 128)', width = 4, dash = 'dash')) %>%
add_trace(y = ~high_2000,
name = 'High 2000',
line = list(color = 'rgb(199, 0, 57) ', width = 4, dash = 'dot')) %>%
add_trace(y = ~low_2000,
name = 'Low 2000',
line = list(color = 'rgb(59, 82, 128)', width = 4, dash = 'dot')) %>%
layout(title = "Average High and Low Temperatures in New York",
xaxis = list(title = "Months"),
yaxis = list (title = "Temperature (degrees F)"))
pdf <- plyr::ddply(datasets::ToothGrowth,
c("supp", "dose"),
summarise,
length=mean(len))
p <- plot_ly(df,
x = ~dose,
y = ~length,
type = 'scatter',
mode = 'lines',
linetype = ~supp,
line = list(color = 'rgb(59, 82, 128)')) %>%
layout(title = 'The Effect of Vitamin C on Tooth Growth in Guinea Pigs by Supplement Type',
xaxis = list(title = 'Dose in milligrams/day'),
yaxis = list (title = 'Tooth length'))
pdata<- data.frame(x = c(1:15),
y = c(10, 20, NA, 15, 10, 5, 15, NA, 20, 10, 10, 15, 25, 20, 10))
p <- plot_ly(data,
x = ~x,
y = ~y,
name = "Gaps",
type = 'scatter',
mode = 'lines',
line = list(color = c("#C70039"))) %>%
add_trace(y = ~y - 5,
name = "<b>No</b> Gaps",
connectgaps = TRUE,
line = list(color = c("#581845")))
pdata<- data.frame(x = c(1:5),
y = c(1, 3, 2, 3, 1))
p <- data%>%
plot_ly(x = ~x) %>%
add_lines(y = ~y,
name = "linear",
line = list(shape = "linear", color = "#440154FF")) %>%
add_lines(y = ~y + 5,
name = "spline",
line = list(shape = "spline", color = "#404688FF")) %>%
add_lines(y = ~y + 10,
name = "vhv",
line = list(shape = "vhv", color = "#287C8EFF")) %>%
add_lines(y = ~y + 15,
name = "hvh",
line = list(shape = "hvh", color = "#27AD81FF")) %>%
add_lines(y = ~y + 20,
name = "vh",
line = list(shape = "vh", color = "#8FD744FF")) %>%
add_lines(y = ~y + 25,
name = "hv",
line = list(shape = "hv", color = "#E3E418FF"))
pdata<-data.frame(x = c(2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013),
y_television = c(74, 82, 80, 74, 73, 72, 74, 70, 70, 66, 66, 69),
y_internet = c(13, 14, 20, 24, 20, 24, 24, 40, 35, 41, 43, 50))
p <- plot_ly(data, x = ~x) %>%
add_trace(y = ~y_television,
type = 'scatter',
mode = 'lines',
line = list(color = 'rgba(199,0,57,1)', width = 2)) %>%
add_trace(y = ~y_internet,
type = 'scatter',
mode = 'lines',
line = list(color = 'rgba(49,130,189, 1)', width = 4)) %>%
add_trace(x = ~c(x[1], x[12]),
y = ~c(y_television[1], y_television[12]),
type = 'scatter',
mode = 'markers',
marker = list(color = 'rgba(199,0,57,1)', size = 8)) %>%
add_trace(x = ~c(x[1], x[12]),
y = ~c(y_internet[1], y_internet[12]),
type = 'scatter',
mode = 'markers',
marker = list(color = 'rgba(49,130,189, 1)', size = 12)) %>%
layout(title = "Main Source for News",
xaxis = list(title = "",
showline = TRUE,
showgrid = FALSE,
showticklabels = TRUE,
linecolor = 'rgb(204, 204, 204)',
linewidth = 2,
autotick = FALSE,
ticks = 'outside',
tickcolor = 'rgb(204, 204, 204)',
tickwidth = 2,
ticklen = 5,
tickfont = list(family = 'Arial',
size = 12,
color = 'rgb(82, 82, 82)')),
yaxis = list(title = "",
showgrid = FALSE,
zeroline = FALSE,
showline = FALSE,
showticklabels = FALSE),
margin = list(autoexpand = FALSE,
l = 100,
r = 100,
t = 110),
autosize = FALSE,
showlegend = FALSE,
annotations = list(xref = 'paper', #television 1
yref = 'y',
x = 0.05,
y = data$y_television[1],
xanchor = 'right',
yanchor = 'middle',
text = ~paste('Television ', data$y_television[1], '%'),
font = list(family = 'Arial',
size = 16,
color = 'rgba(199,0,57,1)'),
showarrow = FALSE)) %>%
layout(annotations = list(xref = 'paper', # internet 1
yref = 'y',
x = 0.05,
y = data$y_internet[1],
xanchor = 'right',
yanchor = 'middle',
text = ~paste('Internet ', data$y_internet[1], '%'),
font = list(family = 'Arial',
size = 16,
color = 'rgba(49,130,189, 1)'),
showarrow = FALSE)) %>%
layout(annotations = list(xref = 'paper', #television2
x = 0.95,
y = data$y_television[12],
xanchor = 'left',
yanchor = 'middle',
text = paste('Television ', data$y_television[12], '%'),
font = list(family = 'Arial',
size = 16,
color= 'rgba(199,0,57,1)'),
showarrow = FALSE)) %>%
layout(annotations = list(xref = 'paper', # internet 2
x = 0.95,
y = data$y_internet[12],
xanchor = 'left',
yanchor = 'middle',
text = paste('Internet ', data$y_internet[12], '%'),
font = list(family = 'Arial',
size = 16,
color = 'rgba(49,130,189, 1)'),
showarrow = FALSE))
pdata(mtcars)
mtcars %>%
plot_ly( x = ~hp,
y = ~mpg,
type = "scatter",
color = I("black"),
size = ~cyl) %>%
add_lines(y = ~fitted(loess(mpg ~ hp)),
line = list(color = '#07A4B5'),
name = "Loess Smoother",
showlegend = TRUE) %>%
layout(xaxis = list(title = 'horse power '),
yaxis = list(title = 'Miles/(US) gallon'),
legend = list(x = 0.80, y = 0.90))data<- data.frame(month = c('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'),
high_2014 = c(28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9),
low_2014 = c(12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1)) %>%
mutate(average_2014 = (high_2014+low_2014)/2,
month = factor(.$month,levels=.$month))
p <- plot_ly(data,
x = ~month,
y = ~high_2014,
type = 'scatter',
mode = 'lines',
line = list(color = 'transparent'),
showlegend = FALSE,
name = 'High 2014') %>%
add_trace(y = ~low_2014,
type = 'scatter',
mode = 'lines',
fill = 'tonexty',
fillcolor='rgba(0,100,80,0.2)',
line = list(color = 'transparent'),
showlegend = FALSE,
name = 'Low 2014') %>%
add_trace(x = ~month,
y = ~average_2014,
type = 'scatter',
mode = 'lines',
line = list(color='rgb(0,100,80)'),
name = 'Average') %>%
layout(title = "Average, High and Low Temperatures in New York",
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='rgb(229,229,229)',
xaxis = list(title = "Months",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE),
yaxis = list(title = "Temperature (degrees F)",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE))
prequire(viridis)
dens <- with(diamonds, tapply(price, INDEX = cut, density))
df <- data.frame(x = unlist(lapply(dens, "[[", "x")),
y = unlist(lapply(dens, "[[", "y")),
cut = rep(names(dens), each = length(dens[[1]]$x)))
p <- plot_ly(df,
x = ~x,
y = ~y,
color = ~cut,
colors=viridis_pal(option = "D")(5)) %>%
add_lines()
pdata(USAccDeaths)
p <- plot_ly() %>%
add_lines(x = time(USAccDeaths),
y = USAccDeaths,
color = I("#2C728EFF"),
name = "observed")
pTambién se pueden inclustar plots.
data("EUStockMarkets")
stocks <- as.data.frame(EuStockMarkets) %>%
gather(index, price) %>%
mutate(time = rep(time(EuStockMarkets), 4))
p<-plot_ly(stocks,
x = ~time,
y = ~price,
color = ~index,
colors=viridis_pal(option = "C")(4),
type = 'scatter',
mode = 'markers') %>%
layout(title = 'EU Stock Markets over Time',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE))
prequire(forecast)
fit <- ets(USAccDeaths)
fcst <- forecast(fit, h = 48, level = c(80, 95))
p <- plot_ly() %>%
add_lines(x = time(USAccDeaths),
y = USAccDeaths,
color = I("black"),
name = "observed") %>%
add_ribbons(x = time(fcst$mean),
ymin = fcst$lower[, 2],
ymax = fcst$upper[, 2],
color = I("gray95"),
name = "95% confidence") %>%
add_ribbons(x = time(fcst$mean),
ymin = fcst$lower[, 1],
ymax = fcst$upper[, 1],
color = I("gray80"),
name = "80% confidence") %>%
add_lines(x = time(fcst$mean),
y = fcst$mean,
color = I("blue"),
name = "prediction")
pggplotdata("USArrests")
sample_data <- tibble(State = state.name,
Region = state.region) %>%
bind_cols(USArrests)
p <-sample_data %>%
ggplot(aes(x=Murder,
y=Assault,
size=Rape,
color=UrbanPop,
label=State)) +
geom_point(alpha=0.8) +
geom_text(aes(label = State), hjust = 0, vjust = 0) +
theme_minimal() +
scale_size_continuous(range = c(1, 7)) +
scale_color_viridis() +
labs(x="Murder",
y="Assault",
size="Rape",
color="UrbanPop")
ggplotly(p) La función plotly_build ayuda a modificar la descripción de cada punto de la información de cada variable, así que, puede ser útil para anular los valores predeterminados por ggplotly o para depurar errores de representación.
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv")
p <- plot_ly(data,
x = ~Women,
y = ~Men,
text = ~School,
type = 'scatter',
mode = 'markers',
color = ~Gap,
colors = 'Reds',
marker = list(size = ~Gap, opacity = 0.5)) %>%
layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE))
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
mutate(State=as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania',
'New Jersey', 'Illinois', 'Washington DC','Massachusetts',
'Connecticut', 'New York', 'North Carolina', 'New Hampshire',
'New York', 'Indiana','New York', 'Michigan',
'Rhode Island', 'California', 'Georgia', 'California', 'California')))
p <- plot_ly(data,
x = ~Women,
y = ~Men,
text = ~School,
type = 'scatter',
mode = 'markers',
size = ~Gap,
color = ~State,
colors = 'Set2',
marker = list(opacity = 0.6, sizemode = 'diameter')) %>%
layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE),
showlegend = FALSE)
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
mutate(State=as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania',
'New Jersey', 'Illinois', 'Washington DC','Massachusetts',
'Connecticut', 'New York', 'North Carolina', 'New Hampshire',
'New York', 'Indiana','New York', 'Michigan',
'Rhode Island', 'California', 'Georgia', 'California', 'California')))
p <- plot_ly(data,
x = ~Women,
y = ~Men,
text = ~School,
type = 'scatter',
mode = 'markers',
size = ~Gap,
color = ~State,
colors = 'Set2',
sizes = c(10, 50), #Choosing the range of the bubbles' sizes
marker = list(opacity = 0.7, sizemode = 'diameter')) %>%
layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE),
showlegend = FALSE)
psizerefPara escalar el tamaño de la burbuja, se usa el atributo sizeref. Es recomendable usar la siguiente fórmula para calcular un valor de sizeref .
\[sizeref = 2.0 *\frac{\text{max (matriz de valores de tamaño)}} {\text{tamaño de marcador máximo deseado ** 2}}\] Tenga en cuenta que establecer sizeref en un valor mayor que 1 disminuye los tamaños de marcador representados, mientras establece sizeref en menos de 1 aumenta el tamaño de los marcadores renderizados. Consulte https://plotly.com/python/reference/#scatter-marker-sizeref para obtener más información.
data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
mutate(State=as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania',
'New Jersey', 'Illinois', 'Washington DC','Massachusetts',
'Connecticut', 'New York', 'North Carolina', 'New Hampshire',
'New York', 'Indiana','New York', 'Michigan',
'Rhode Island', 'California', 'Georgia', 'California', 'California')))
#Use the ideal sizeref value
desired_maximum_marker_size <- 40
your_list_of_size_values <- data['Gap']
sizeref <- 2.0 * max(your_list_of_size_values) / (desired_maximum_marker_size**2)
p <- plot_ly(data,
x = ~Women,
y = ~Men,
text = ~School,
type = 'scatter',
mode = 'markers',
size = ~Gap,
color = ~State,
colors = 'Set2',
sizes = c(10, 50),
marker = list(size=40, # El tamaño máximo deseado
opacity = 0.5,
sizemode = 'area',
sizeref =10)) %>%
layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE),
showlegend = FALSE)
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
mutate(State=as.factor(c('Massachusetts', 'California', 'Massachusetts', 'Pennsylvania',
'New Jersey', 'Illinois', 'Washington DC','Massachusetts',
'Connecticut', 'New York', 'North Carolina', 'New Hampshire',
'New York', 'Indiana','New York', 'Michigan',
'Rhode Island', 'California', 'Georgia', 'California', 'California')))
p <- plot_ly(data,
x = ~Women,
y = ~Men,
type = 'scatter',
mode = 'markers',
size = ~Gap,
color = ~State,
colors = 'Set2',
sizes = c(20, 50),
marker = list(opacity = 0.8, sizemode = 'diameter'),
hoverinfo = 'text',
text = ~paste('School:', School, '<br>Gender Gap:', Gap))%>%
layout(title = 'Gender Gap in Earnings per University',
xaxis = list(showgrid = FALSE),
yaxis = list(showgrid = FALSE),
showlegend = FALSE)
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv") %>%
filter(year==2007) %>%
arrange(continent,country) %>%
mutate(size= sqrt(pop*2.666051223553066e-05)) #sqrt(pop*slope)
colors <- c('#4AC6B7', '#1972A4', '#965F8A', '#FF7070', '#C61951')
p <- plot_ly(data,
x = ~gdpPercap,
y = ~lifeExp,
color = ~continent,
size = ~size,
colors = colors,
type = 'scatter',
mode = 'markers',
sizes = c(min(data$size), max(data$size)),
marker = list(symbol = 'circle',
sizemode = 'diameter',
line = list(width = 2, color = '#FFFFFF')),
text = ~paste('Country:', country,
'<br>Life Expectancy:', lifeExp,
'<br>GDP:', gdpPercap,
'<br>Pop.:', pop)) %>%
layout(title = 'Life Expectancy v. Per Capita GDP, 2007',
xaxis = list(title = 'GDP per capita (2000 dollars)',
gridcolor = 'rgb(255, 255, 255)',
range = c(2.003297660701705, 5.191505530708712),
type = 'log',
zerolinewidth = 1,
ticklen = 5,
gridwidth = 2),
yaxis = list(title = 'Life Expectancy (years)',
gridcolor = 'rgb(255, 255, 255)',
range = c(36.12621671352166, 91.72921793264332),
zerolinewidth = 1,
ticklen = 5,
gridwith = 2),
paper_bgcolor = 'rgb(243, 243, 243)',
plot_bgcolor = 'rgb(243, 243, 243)')
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
arrange(Men)
p <- plot_ly(data,
x = ~Women,
y = ~School,
name = "Women",
type = 'scatter',
mode = "markers",
marker = list(color = "#3B528BFF")) %>%
add_trace(x = ~Men,
y = ~School,
name = "Men",
type = 'scatter',
mode = "markers",
marker = list(color = "#47C16EFF")) %>%
layout(title = "Gender earnings disparity",
xaxis = list(title = "Annual Salary (in thousands)"),
margin = list(l = 100))
pdata <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/school_earnings.csv") %>%
mutate(School = factor(.$School,levels=.$School))
p <- plot_ly(data,
color = I("gray80")) %>%
add_segments(x = ~Women,
xend = ~Men,
y = ~School,
yend = ~School,
showlegend = FALSE) %>%
add_markers(x = ~Women,
y = ~School,
name = "Women",
color = I("#3B528BFF")) %>%
add_markers(x = ~Men,
y = ~School,
name = "Men",
color = I("#47C16EFF")) %>%
layout(title = "Gender earnings disparity",
xaxis = list(title = "Annual Salary (in thousands)"),
margin = list(l = 65))
pdata <- data.frame(trace_0 = rnorm(100, mean = 5),
trace_1 = rnorm(100, mean = 0),
trace_2 = rnorm(100, mean = -5),
x = c(1:100))
p <- plot_ly(data,
x = ~x) %>%
add_trace(y = ~trace_0,
name = 'trace 0',
mode = 'lines') %>%
add_trace(y = ~trace_1,
name = 'trace 1',
mode = 'lines+markers') %>%
add_trace(y = ~trace_2,
name = 'trace 2',
mode = 'markers')
pTambién es posible pasar el primer gráfico en la función plot_ly. En tales casos, se debe especificar el tipo de gráfico, como se muestra a continuación:
data <- data.frame(trace_0 = rnorm(100, mean = 5),
trace_1 = rnorm(100, mean = 0),
trace_2 = rnorm(100, mean = -5),
x = c(1:100))
p <- plot_ly(data,
x = ~x,
y = ~trace_0,
name = 'trace 0',
type = 'scatter',
mode = 'lines') %>%
add_trace(y = ~trace_1,
name = 'trace 1',
mode = 'lines+markers') %>%
add_trace(y = ~trace_2,
name = 'trace 2',
mode = 'markers')
pdata <- airquality%>%
filter(Month == 9)%>%
mutate(Date = as.Date(paste(.$Month, .$Day, 1973, sep = "."), format = "%m.%d.%Y"))
p <- plot_ly(data) %>%
add_trace(x = ~Date,
y = ~Wind,
type = 'bar',
name = 'Wind',
marker = list(color = '#C9EFF9'),
hoverinfo = "text",
text = ~paste(Wind, ' mph')) %>%
add_trace(x = ~Date,
y = ~Temp,
type = 'scatter',
mode = 'lines',
name = 'Temperature',
yaxis = 'y2',
line = list(color = '#45171D'),
hoverinfo = "text",
text = ~paste(Temp, '°F')) %>%
layout(title = 'New York Wind and Temperature Measurements for September 1973',
xaxis = list(title = ""),
yaxis = list(side = 'left',
title = 'Wind in mph',
showgrid = FALSE,
zeroline = FALSE),
yaxis2 = list(side = 'right',
overlaying = "y",
title = 'Temperature in degrees F',
showgrid = FALSE,
zeroline = FALSE))
pp <- plot_ly(mtcars,
x = ~disp,
color = I("black")) %>%
add_markers(y = ~mpg,
text = rownames(mtcars),
showlegend = FALSE) %>%
add_lines(y = ~fitted(loess(mpg ~ disp)),
line = list(color = '#07A4B5'),
name = "Loess Smoother",
showlegend = TRUE) %>%
layout(xaxis = list(title = 'Displacement (cu.in.)'),
yaxis = list(title = 'Miles/(US) gallon'),
legend = list(x = 0.80, y = 0.90))
prequire(broom)
data <- loess(mpg ~ disp, data = mtcars)
p <- plot_ly(mtcars,
x = ~disp,
color = I("black")) %>%
add_markers(y = ~mpg,
text = rownames(mtcars),
showlegend = FALSE) %>%
add_lines(y = ~fitted(loess(mpg ~ disp)),
line = list(color = 'rgba(7, 164, 181, 1)'),
name = "Loess Smoother") %>%
add_ribbons(data = augment(data),
ymin = ~.fitted - 1.96 * .se.fit,
ymax = ~.fitted + 1.96 * .se.fit,
line = list(color = 'rgba(7, 164, 181, 0.05)'),
fillcolor = 'rgba(7, 164, 181, 0.2)',
name = "Standard Error") %>%
layout(xaxis = list(title = 'Displacement (cu.in.)'),
yaxis = list(title = 'Miles/(US) gallon'),
legend = list(x = 0.80, y = 0.90))
pdata <- data.frame(Animals = c("giraffes", "orangutans", "monkeys") ,
SF_Zoo = c(20, 14, 23),
LA_Zoo = c(12, 18, 29))
p <- plot_ly(data,
x = ~Animals,
y = ~SF_Zoo,
type = 'bar',
name = 'SF Zoo',
color=I("#FF5733")) %>%
add_trace(y = ~LA_Zoo,
name = 'LA Zoo',
color=I("#C70039")) %>%
layout(yaxis = list(title = 'Count'),
barmode = 'group')
pdata <- data.frame(Animals = c("giraffes", "orangutans", "monkeys") ,
SF_Zoo = c(20, 14, 23),
LA_Zoo = c(12, 18, 29))
p <- plot_ly(data,
x = ~Animals,
y = ~SF_Zoo,
type = 'bar',
name = 'SF Zoo',
color=I("#FF5733")) %>%
add_trace(y = ~LA_Zoo,
name = 'LA Zoo',
color=I("#C70039")) %>%
layout(yaxis = list(title = 'Count'),
barmode = 'stack')
pdata <- data.frame(x = c('Product A', 'Product B', 'Product C'),
y = c(20, 14, 23),
text = c('27% market share', '24% market share', '19% market share'))
p<- plot_ly(data,
x = ~x,
y = ~y,
type = 'bar',
text = text,
marker = list(color = 'rgb(185, 0, 86)',
line = list(color = 'rgb(132, 19, 72)', width = 1.5))) %>%
layout(title = "January 2013 Sales Report",
xaxis = list(title = ""),
yaxis = list(title = ""))
pdata <- data.frame(x = c('Product A', 'Product B', 'Product C'),
y = c(20, 14, 23),
text = c('27% market share', '24% market share', '19% market share'))
p<- plot_ly(data,
x = ~ x,
y = ~ y,
type = 'bar',
text = data$y,
textposition = 'auto',
marker = list(color = 'rgba(213,0,99,0.5)',
line = list(color = 'rgb(213,0,99)', width = 1.5))) %>%
layout(title = "January 2013 Sales Report",
xaxis = list(title = ""),
yaxis = list(title = ""))
pdata <- data.frame(x = c('Product A', 'Product B', 'Product C'),
y = c(20, 14, 23),
y2 = c(16,12,27) ,
text = c('27% market share', '24% market share', '19% market share'))
p<- data %>%
plot_ly() %>%
add_trace(x = ~x,
y = ~y,
type = 'bar',
text = data$y,
textposition = 'auto',
marker = list(color = 'rgb(158,202,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
add_trace(x = ~x,
y = ~y2,
type = 'bar',
text = data$y2,
textposition = 'auto',
marker = list(color = 'rgb(58,200,225)',
line = list(color = 'rgb(8,48,107)', width = 1.5))) %>%
layout(title = "January 2013 Sales Report",
barmode = 'group',
xaxis = list(title = ""),
yaxis = list(title = ""))
pdata<- data.frame(x = c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
y1 = c(20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17),
y2 = c(19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16)) %>%
mutate(x = factor(x,levels = .$x))
p <- plot_ly(data,
x = ~x,
y = ~y1,
type = 'bar',
name = 'Primary Product',
marker = list(color = 'rgb(49,130,189)')) %>%
add_trace(y = ~y2,
name = 'Secondary Product',
marker = list(color = 'rgb(204,204,204)')) %>%
layout(xaxis = list(title = "", tickangle = -45),
yaxis = list(title = ""),
margin = list(b = 100),
barmode = 'group')
pdata<- data.frame(x = c('Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E'),
y = c(20, 14, 23, 25, 22))
p <- plot_ly(data,
x = ~x,
y = ~y,
type = 'bar',
marker =list(color= c('rgb(218,247,166)',
'rgb(255,195,0)',
'rgb(255,87,51)',
'rgb(199,0,57)',
'rgb(144,12,63)'))) %>%
layout(title = "Features",
xaxis = list(title = ""),
yaxis = list(title = ""))
pdata<- data.frame(x = c(1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012),
roW = c(219, 146, 112, 127, 124, 180, 236, 207, 236, 263, 350, 430, 474, 526, 488, 537, 500, 439),
China = c(16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270, 299, 340, 403, 549, 499))
p <- plot_ly(data,
x = ~x,
y = ~roW,
type = 'bar',
name = 'Rest of the World',
marker = list(color = 'rgb(55, 83, 109)')) %>%
add_trace(y = ~China,
name = 'China',
marker = list(color = 'rgb(26, 118, 255)')) %>%
layout(title = 'US Export of Plastic Scrap',
xaxis = list(title = "",
tickfont = list(size = 14, color = 'rgb(107, 107, 107)')),
yaxis = list(title = 'USD (millions)',
titlefont = list(size = 16, color = 'rgb(107, 107, 107)'),
tickfont = list(size = 14, color = 'rgb(107, 107, 107)')),
legend = list(x = 0,
y = 1,
bgcolor = 'rgba(255, 255, 255, 0)',
bordercolor = 'rgba(255, 255, 255, 0)'),
barmode = 'group',
bargap = 0.15,
bargroupgap = 0.1)
pdata<- data.frame(x = c('Product<br>Revenue', 'Services<br>Revenue', 'Total<br>Revenue', 'Fixed<br>Costs', 'Variable<br>Costs', 'Total<br>Costs', 'Total'),
y = c(400, 660, 660, 590, 400, 400, 340),
base = c(0, 430, 0, 570, 370, 370, 0),
revenue = c(430, 260, 690, 0, 0, 0, 0),
costs = c(0, 0, 0, 120, 200, 320, 0),
profit = c(0, 0, 0, 0, 0, 0, 370),
text = c('$430K', '$260K', '$690K', '$-120K', '$-200K', '$-320K', '$370K')) %>%
mutate(x=factor(x,levels=.$x))
p <- plot_ly(data,
x = ~x,
y = ~base,
type = 'bar',
marker = list(color = 'rgba(1,1,1, 0.0)')) %>%
add_trace(y = ~revenue,
marker = list(color = 'rgba(55, 128, 191, 0.7)',
line = list(color = 'rgba(55, 128, 191, 0.7)', width = 2))) %>%
add_trace(y = ~costs,
marker = list(color = 'rgba(219, 64, 82, 0.7)',
line = list(color = 'rgba(219, 64, 82, 1.0)', width = 2))) %>%
add_trace(y = ~profit,
marker = list(color = 'rgba(50, 171, 96, 0.7)',
line = list(color = 'rgba(50, 171, 96, 1.0)', width = 2))) %>%
layout(title = 'Annual Profit - 2015',
xaxis = list(title = ""),
yaxis = list(title = ""),
barmode = 'stack',
paper_bgcolor = 'rgba(245, 246, 249, 1)',
plot_bgcolor = 'rgba(245, 246, 249, 1)',
showlegend = FALSE) %>%
add_annotations(text = data$text,
x = data$x,
y = data$y,
xref = "x",
yref = "y",
font = list(family = 'Arial',
size = 14,
color = 'rgba(245, 246, 249, 1)'),
showarrow = FALSE)
pejemplos de gráficos de barras horizontales https://plotly.com/r/horizontal-bar-charts/
data<- data.frame(y = c('giraffes', 'orangutans', 'monkeys'),
SF_Zoo = c(20, 14, 23),
LA_Zoo = c(12, 18, 29))
p <- plot_ly(data,
x = ~SF_Zoo,
y = ~y,
type = 'bar',
orientation = 'h',
name = 'SF Zoo',
marker = list(color = 'rgba(246, 78, 139, 0.6)',
line = list(color = 'rgba(246, 78, 139, 1.0)', width = 3))) %>%
add_trace(x = ~LA_Zoo,
name = 'LA Zoo',
marker = list(color = 'rgba(58, 71, 80, 0.6)',
line = list(color = 'rgba(58, 71, 80, 1.0)', width = 3))) %>%
layout(barmode = 'stack',
xaxis = list(title = ""),
yaxis = list(title =""))
pdata<- data.frame(y = c('The course was effectively<br>organized',
'The course developed my<br>abilities and skills for<br>the subject',
'The course developed my<br>ability to think critically about<br>the subject',
'I would recommend this<br>course to a friend'),
x1 = c(21, 24, 27, 29),
x2 = c(30, 31, 26, 24),
x3 = c(21, 19, 23, 15),
x4 = c(16, 15, 11, 18),
x5 = c(12, 11, 13, 14))
top_labels = c('Strongly<br>agree', 'Agree', 'Neutral', 'Disagree', 'Strongly<br>disagree')
p <- data%>%
plot_ly(x = ~x1,
y = ~y,
type = 'bar',
orientation = 'h',
marker = list(color = 'rgba(38, 24, 74, 0.8)',
line = list(color = 'rgb(248, 248, 249)', width = 1))) %>%
add_trace(x = ~x2,
marker = list(color = 'rgba(71, 58, 131, 0.8)')) %>%
add_trace(x = ~x3,
marker = list(color = 'rgba(122, 120, 168, 0.8)')) %>%
add_trace(x = ~x4,
marker = list(color = 'rgba(164, 163, 204, 0.85)')) %>%
add_trace(x = ~x5, marker = list(color = 'rgba(190, 192, 213, 1)')) %>%
layout(xaxis = list(title = "",
showgrid = FALSE,
showline = FALSE,
showticklabels = FALSE,
zeroline = FALSE,
domain = c(0.15, 1)),
yaxis = list(title = "",
showgrid = FALSE,
showline = FALSE,
showticklabels = FALSE,
zeroline = FALSE),
barmode = 'stack',
paper_bgcolor = 'rgb(248, 248, 255)',
plot_bgcolor = 'rgb(248, 248, 255)',
margin = list(l = 120, r = 10, t = 140, b = 80),
showlegend = FALSE) %>%
add_annotations(xref = 'paper', # labeling the y-axis
yref = 'y',
x = 0.14,
y = data$y,
xanchor = 'right',
text = data$y,
font = list(family = 'Arial',
size = 12,
color = 'rgb(67, 67, 67)'),
showarrow = FALSE,
align = 'right') %>%
add_annotations(xref = 'x', # labeling the percentages of each bar (x_axis)
yref = 'y',
x = data$x1 / 2,
y = data$y,
text = paste(data[,"x1"], '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(248, 248, 255)'),
showarrow = FALSE) %>%
add_annotations(xref = 'x',
yref = 'y',
x = data$x1 + data$x2 / 2,
y = data$y,
text = paste(data[,"x2"], '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(248, 248, 255)'),
showarrow = FALSE) %>%
add_annotations(xref = 'x',
yref = 'y',
x = data$x1 + data$x2 + data$x3 / 2,
y = data$y,
text = paste(data[,"x3"], '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(248, 248, 255)'),
showarrow = FALSE) %>%
add_annotations(xref = 'x',
yref = 'y',
x = data$x1 + data$x2 + data$x3 + data$x4 / 2,
y = data$y,
text = paste(data[,"x4"], '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(248, 248, 255)'),
showarrow = FALSE) %>%
add_annotations(xref = 'x',
yref = 'y',
x = data$x1 + data$x2 + data$x3 + data$x4 + data$x5 / 2,
y = data$y,
text = paste(data[,"x5"], '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(248, 248, 255)'),
showarrow = FALSE) %>%
add_annotations(xref = 'x', # labeling the first Likert scale (on the top)
yref = 'paper',
x = c(21 / 2,
21 + 30 / 2,
21 + 30 + 21 / 2,
21 + 30 + 21 + 16 / 2,
21 + 30 + 21 + 16 + 12 / 2),
y = 1.15,
text = top_labels,
font = list(family = 'Arial',
size = 12,
color = 'rgb(67, 67, 67)'),
showarrow = FALSE)
pdata<- data.frame(y = c('Japan', 'United Kingdom', 'Canada', 'Netherlands', 'United States',
'Belgium', 'Sweden', 'Switzerland'),
x_saving =c(1.3586, 2.2623000000000002, 4.9821999999999997, 6.5096999999999996,
7.4812000000000003, 7.5133000000000001, 15.2148, 17.520499999999998),
x_net_worth = c(93453.919999999998, 81666.570000000007, 69889.619999999995, 78381.529999999999,
141395.29999999999, 92969.020000000004, 66090.179999999993, 122379.3))
p1 <- data%>%
plot_ly(x = ~x_saving,
y = ~reorder(y, x_saving),
name = 'Household savings, percentage of household disposable income',
type = 'bar',
orientation = 'h',
marker = list(color = 'rgba(50, 171, 96, 0.6)',
line = list(color = 'rgba(50, 171, 96, 1.0)', width = 1))) %>%
layout(yaxis = list(showgrid = FALSE,
showline = FALSE,
showticklabels = TRUE,
domain= c(0, 0.85)),
xaxis = list(zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = TRUE)) %>%
add_annotations(xref = 'x1',
yref = 'y',
x = data$x_saving * 2.1 + 3,
y = data$y,
text = paste(round(data$x_saving, 2), '%'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(50, 171, 96)'),
showarrow = FALSE)
p2 <- data%>%
plot_ly(x = ~x_net_worth,
y = ~reorder(.$y, .$x_saving),
name = 'Household net worth, Million USD/capita',
type = 'scatter',
mode = 'lines+markers',
line = list(color = 'rgb(128, 0, 128)')) %>%
layout(yaxis = list(showgrid = FALSE,
showline = TRUE,
showticklabels = FALSE,
linecolor = 'rgba(102, 102, 102, 0.8)',
linewidth = 2,
domain = c(0, 0.85)),
xaxis = list(zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = TRUE,
side = 'top',
dtick = 25000)) %>%
add_annotations(xref = 'x2',
yref = 'y',
x = data$x_net_worth,
y = data$y,
text = paste(data$x_net_worth, 'M'),
font = list(family = 'Arial',
size = 12,
color = 'rgb(128, 0, 128)'), showarrow = FALSE)
p <- subplot(p1, p2) %>%
layout(title = 'Household savings & net worth for eight OECD countries',
legend = list(x = 0.029,
y = 1.038,
font = list(size = 10)),
margin = list(l = 100, r = 20, t = 70, b = 70),
paper_bgcolor = 'rgb(248, 248, 255)',
plot_bgcolor = 'rgb(248, 248, 255)') %>%
add_annotations(xref = 'paper',
yref = 'paper',
x = -0.14,
y = -0.15,
text = paste('OECD (2015), Household savings (indicator), Household net worth (indicator). doi: 10.1787/cfc6f499-en (Accessed on 05 June 2015)'),
font = list(family = 'Arial',
size = 10,
color = 'rgb(150,150,150)'),
showarrow = FALSE)
pPara generar un rellenar el interior de un plot de área, se usa el atributo fill='tozeroy'.
diamonds1<-diamonds%>%filter(cut=="Fair")
density1 <- density(diamonds1$carat)
diamonds2 <- diamonds%>%filter(cut=="Ideal")
density2 <- density(diamonds2$carat)
p <- plot_ly(x = ~density1$x,
y = ~density1$y,
type = 'scatter',
mode = 'lines',
name = 'Fair cut',
fill = 'tozeroy') %>%
add_trace(x = ~density2$x,
y = ~density2$y,
name = 'Ideal cut',
fill = 'tozeroy') %>%
layout(xaxis = list(title = 'Carat'),
yaxis = list(title = 'Density'))
pSeleccionando puntos flotantes
p <- plot_ly() %>%
add_trace(x = c(0,0.5,1,1.5,2),
y = c(0,1,2,1,0),
type = 'scatter',
fill = 'toself',
fillcolor = '#ab63fa',
hoveron = 'points+fills',
marker = list(color = '#ab63fa'),
line = list(color = '#ab63fa'),
text = "Points + Fills",
hoverinfo = 'text') %>%
add_trace(x = c(3,3.5,4,4.5,5),
y = c(0,1,2,1,0),
type = 'scatter',
fill = 'toself',
fillcolor = '#e763fa',
hoveron = 'points',
marker = list(color = '#e763fa'),
line = list(color = '#e763fa'),
text = "Points only",
hoverinfo = 'text') %>%
layout(title = "hover on <i>points</i> or <i>fill</i>",
xaxis = list(range = c(0,5.2)),
yaxis = list(range = c(0,3)))
pdiamonds1<-diamonds%>%filter(cut=="Fair")
density1 <- density(diamonds1$carat)
diamonds2 <- diamonds%>%filter(cut=="Ideal")
density2 <- density(diamonds2$carat)
p <- plot_ly(x = ~density1$x,
y = ~density1$y,
type = 'scatter',
mode = 'lines',
name = 'Fair cut',
fill = 'tozeroy',
fillcolor = 'rgba(165, 40, 88, 0.7)',
line = list(width = 0.5,color ='rgba(165, 40, 88, 1)')) %>%
add_trace(x = ~density2$x,
y = ~density2$y,
name = 'Ideal cut',
fill = 'tozeroy',
fillcolor = 'rgba(88, 24, 69, 0.7)') %>%
layout(xaxis = list(title = 'Carat',color ='rgba(88, 24, 69, 0.1)'),
yaxis = list(title = 'Density'))
pPara crear un gráfico de área sin líneas se utiliza el atributo mode="none".
diamonds1<-diamonds%>%filter(cut=="Fair")
density1 <- density(diamonds1$carat)
diamonds2 <- diamonds%>%filter(cut=="Ideal")
density2 <- density(diamonds2$carat)
p <- plot_ly(x = ~density1$x,
y = ~density1$y,
type = 'scatter',
mode = 'none',
name = 'Fair cut',
fill = 'tozeroy',
fillcolor = 'rgba(165, 40, 88, 0.7)') %>%
add_trace(x = ~density2$x,
y = ~density2$y,
name = 'Ideal cut',
fill = 'tozeroy',
fillcolor = 'rgba(88, 24, 69, 0.7)') %>%
layout(xaxis = list(title = 'Carat'),
yaxis = list(title = 'Density'))
pdata<- data.frame(month = c('January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'),
high_2014 = c(28.8, 28.5, 37.0, 56.8, 69.7, 79.7, 78.5, 77.8, 74.1, 62.6, 45.3, 39.9),
low_2014 = c(12.7, 14.3, 18.6, 35.5, 49.9, 58.0, 60.0, 58.6, 51.7, 45.2, 32.2, 29.1)) %>%
mutate(average_2014 = (high_2014+low_2014)/2,
month = factor(.$month,levels=.$month))
p <- plot_ly(data,
x = ~month,
y = ~high_2014,
type = 'scatter',
mode = 'lines',
line = list(color = 'rgba(0,100,80,1)'),
showlegend = FALSE,
name = 'High 2014') %>%
add_trace(y = ~low_2014,
type = 'scatter',
mode = 'lines',
fill = 'tonexty',
fillcolor='rgba(0,100,80,0.2)',
line = list(color = 'rgba(0,100,80,1)'),
showlegend = FALSE,
name = 'Low 2014') %>%
layout(title = "High and Low Temperatures in New York",
paper_bgcolor='rgb(255,255,255)',
plot_bgcolor='rgb(229,229,229)',
xaxis = list(title = "Months",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE),
yaxis = list(title = "Temperature (degrees F)",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE))
pdata <- t(USPersonalExpenditure)%>%
as.data.frame()%>%
mutate(year=rownames(.))
p <- plot_ly(data,
x = ~year,
y = ~`Food and Tobacco`,
name = 'Food and Tobacco',
type = 'scatter',
mode = 'none',
stackgroup = 'one',
fillcolor = '#F5FF8D') %>%
add_trace(y = ~`Household Operation`,
name = 'Household Operation',
fillcolor = '#50CB86') %>%
add_trace(y = ~`Medical and Health`,
name = 'Medical and Health',
fillcolor = '#4C74C9') %>%
add_trace(y = ~`Personal Care`,
name = 'Personal Care',
fillcolor = '#700961') %>%
add_trace(y = ~`Private Education`,
name = 'Private Education',
fillcolor = '#312F44') %>%
layout(title = 'United States Personal Expenditures by Categories',
xaxis = list(title = "",
showgrid = FALSE),
yaxis = list(title = "Expenditures (in billions of dollars)",
showgrid = FALSE))
pdata <- t(USPersonalExpenditure)%>%
as.data.frame()%>%
mutate(year=rownames(.))
p <- plot_ly(data,
x = ~year,
y = ~`Food and Tobacco`,
name = 'Food and Tobacco',
type = 'scatter',
mode = 'none',
stackgroup = 'one',
groupnorm = 'percent',
fillcolor = '#F5FF8D') %>%
add_trace(y = ~`Household Operation`,
name = 'Household Operation',
fillcolor = '#50CB86') %>%
add_trace(y = ~`Medical and Health`,
name = 'Medical and Health',
fillcolor = '#4C74C9') %>%
add_trace(y = ~`Personal Care`,
name = 'Personal Care',
fillcolor = '#700961') %>%
add_trace(y = ~`Private Education`,
name = 'Private Education',
fillcolor = '#312F44') %>%
layout(title = 'United States Personal Expenditures by Categories',
xaxis = list(title = "",
showgrid = FALSE),
yaxis = list(title = "Expenditures (in billions of dollars)",
showgrid = FALSE))
pEl algoritmo quartilemethod='exclusive' utiliza la mediana para dividir el conjunto de datos ordenado en dos mitades. Si la muestra es impar, no incluye la mediana en ninguna de las dos. Q1 es entonces la mediana de la mitad inferior y Q3 es la mediana de la mitad superior.
El algoritmo quartilemethod='inclusive' también usa la mediana para dividir el conjunto de datos ordenado en dos mitades, pero si la muestra es impar, incluye la mediana en ambas mitades. Q1 es entonces la mediana de la mitad inferior y Q3 la mediana de la mitad superior.
p <- plot_ly(y = list(1,2,3,4,5),
type = "box",
quartilemethod="linear",
name="Linear Quartile Mode",
color=I("#581845")) %>%
add_trace(y = list(1,2,3,4,5),
quartilemethod="inclusive",
name="Inclusive Quartile Mode",
color=I("#900C3F")) %>%
add_trace(y = list(1,2,3,4,5),
quartilemethod="exclusive",
name="Exclusive Quartile Mode",
color=I("#C70039")) %>%
layout(title = "Modifying The Algorithm For Computing Quartiles")
pEsto puede ser útil si ya se ha calculado previamente esos valores o si necesita utilizar un algoritmo diferente al proporcionado.
data<- data.frame(y1 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
y2 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
y3 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25),
y4 = c(0.75, 5.25, 5.5, 6, 6.2, 6.6, 6.80, 7.0, 7.2, 7.5, 7.5, 7.75, 8.15,
8.15, 8.65, 8.93, 9.2, 9.5, 10, 10.25, 11.5, 12, 16, 20.90, 22.3, 23.25))
p <- data%>%
plot_ly(type = 'box') %>%
add_boxplot(y = ~y1,
jitter = 0.6,
pointpos = -1.8,
boxpoints = 'all',
marker = list(color = 'rgba(147,151,144,0.5)',
size=8,
line = list(color = 'rgba(147,151,144,1)')),
name = "All Points") %>%
add_boxplot(y = ~y2,
name = "Only Whiskers",
boxpoints = FALSE,
marker = list(color = 'rgba(255,87,51,0.5)',
line = list(outliercolor = 'rgba(255,87,51,1)',
color = 'rgba(255,87,51,1)'))) %>%
add_boxplot(y = ~y3,
name = "Suspected Outlier",
boxpoints = 'suspectedoutliers',
marker = list(color = 'rgba(244,12,12,0.5)',
outliercolor = 'rgba(244,12,12,0.5)',
line = list(outliercolor = 'rgba(244,12,12,1)',
outlierwidth = 2))) %>%
add_boxplot(y = ~y4,
name = "Whiskers and Outliers",
boxpoints = 'outliers',
marker = list(color = 'rgba(199,0,57,0.5)',
line = list(outliercolor = 'rgba(199,0,57,0.5)',
color = 'rgba(199,0,57,0.5)'))) %>%
layout(title = "Box Plot Styling Outliers")
pdata("USPersonalExpenditure")
data <- data.frame("Categorie"= rownames(USPersonalExpenditure),
USPersonalExpenditure) %>%
select('Categorie', 'X1960')
p<- plot_ly(data,
labels = ~ Categorie,
values = ~ X1960,
marker = list(colors=viridis_pal(option="D")(5)),
type = 'pie') %>%
layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE),
yaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE))
pcolors <- c('rgb(211,94,96)', 'rgb(128,133,133)', 'rgb(144,103,167)', 'rgb(171,104,87)', 'rgb(114,147,203)')
p <- plot_ly(data,
labels = ~Categorie,
values = ~X1960,
type = 'pie',
textposition = 'inside',
textinfo = 'label+percent',
insidetextfont = list(color = '#FFFFFF'),
hoverinfo = 'text',
text = ~paste('$', X1960, ' billions'),
marker = list(colors = colors,
line = list(color = '#FFFFFF', width = 1)), #The 'pull' attribute can also be used to create space between the sectors
showlegend = FALSE)%>%
layout(title = 'United States Personal Expenditures by Categories in 1960',
xaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE),
yaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE))
pPara crear los subplots de un gráfico de pie, se debe usar el dominio. Es importante tener en cuenta que la matriz \(X\) establece la posición horizontal mientras que la matriz \(Y\) establece la posición vertical. Por ejemplo, \(x=[0,0.5]\), \(y=[0,0.5]\) significaría que la posición del gráfico inferior-izquierda.
p <- plot_ly() %>%
add_pie(data = dplyr::count(diamonds, cut),
labels = ~cut,
values = ~n,
name = "Cut",
domain = list(x = c(0, 0.4), y = c(0.4, 1))) %>%
add_pie(data = dplyr::count(diamonds, color),
labels = ~color,
values = ~n,
name = "Color",
domain = list(x = c(0.6, 1), y = c(0.4, 1))) %>%
add_pie(data = dplyr::count(diamonds, clarity),
labels = ~clarity,
values = ~n,
name = "Clarity",
domain = list(x = c(0.25, 0.75), y = c(0, 0.6))) %>%
layout(title = "Pie Charts with Subplots", showlegend = F,
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
pEste ejemplo utiliza un atributo de grid para los suplots. Se hace referencia al destino de fila y columna utilizando el atributo domain.
p<- plot_ly() %>%
add_pie(data = count(diamonds, cut),
labels = ~cut,
values = ~n,
name = "Cut",
domain = list(row = 0, column = 0)) %>%
add_pie(data = count(diamonds, color),
labels = ~color,
values = ~n,
name = "Color",
domain = list(row = 0, column = 1)) %>%
add_pie(data = count(diamonds, clarity),
labels = ~clarity,
values = ~n,
name = "Clarity",
domain = list(row = 1, column = 0)) %>%
add_pie(data = count(diamonds, clarity),
labels = ~clarity,
values = ~n,
name = "Clarity",
marker = list(colors=viridis_pal(option="D")(5)),
domain = list(row = 1, column = 1)) %>%
layout(title = "Pie Charts with Subplots",
showlegend = F,
grid=list(rows=2, columns=2),
xaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE),
yaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE))
pEl atributo insdetextorientation controla la orientación del texto dentro de los sectores. \(\bullet\) 'auto', las etiquetas pueden rotarse automáticamente para ajustarse al tamaño máximo dentro del corte.
\(\bullet\) 'horizontal', "Radial", "Tangencial" obliga al texto a ser horizonatal, radial o tangencial.
plotly puede reducir el tamaño de fuente para ajustar el texto con la orientaciión solicitada.
# Get Manufacturer
mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
p <- mtcars %>%
group_by(manuf) %>%
summarize(count = n()) %>%
plot_ly(labels = ~manuf,
values = ~count,
marker = list(colors=viridis_pal(option="A")(22))) %>%
add_pie(hole = 0.6) %>%
layout(title = "Donut charts using Plotly",
showlegend = F,
xaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE),
yaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE))
pPara obtener más información y opciones de atributos de gráficos plotly_attributes
df <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
p <- df %>%
plot_ly(x = ~day,
y = ~total_bill,
split = ~day,
type = 'violin',
box = list(visible = T),
meanline = list(visible = T)) %>%
layout(xaxis = list(title = "Day"),
yaxis = list(title = "Total Bill",
zeroline = F))
pdf <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
p <- df %>%
plot_ly(type = 'violin') %>%
add_trace(x = ~day[df$sex == 'Male'],
y = ~total_bill[df$sex == 'Male'],
legendgroup = 'M',
scalegroup = 'M',
name = 'M',
box = list(visible = T),
meanline = list(visible = T),
color = I("blue")) %>%
add_trace(x = ~day[df$sex == 'Female'],
y = ~total_bill[df$sex == 'Female'],
legendgroup = 'F',
scalegroup = 'F',
name = 'F',
box = list(visible = T),
meanline = list(visible = T),
color = I("pink")) %>%
layout(xaxis = list (title = "Day"),
yaxis = list(title = "Total Bill", zeroline = F),
violinmode = 'group')
pdf <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
p <- df %>%
plot_ly(type = 'violin') %>%
add_trace(x = ~day[df$smoker == 'Yes'],
y = ~total_bill[df$smoker == 'Yes'],
legendgroup = 'Yes',
scalegroup = 'Yes',
name = 'Yes',
side = 'negative',
box = list(visible = T),
meanline = list(visible = T),
color = I("blue")) %>%
add_trace(x = ~day[df$smoker == 'No'],
y = ~total_bill[df$smoker == 'No'],
legendgroup = 'No',
scalegroup = 'No',
name = 'No',
side = 'positive',
box = list(visible = T),
meanline = list(visible = T),
color = I("green")) %>%
layout(xaxis = list(title = ""),
yaxis = list(title = "", zeroline = F),
violingap = 0,
violingroupgap = 0,
violinmode = 'overlay')
pdf <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/violin_data.csv")
pointposMale <- c(-0.9,-1.1,-0.6,-0.3)
pointposFemale <- c(0.45,1.2,1,0.4)
showLegend <- c(T,F,F,F)
p<-NULL
i = 0
for (i in 1:length(unique(df$day))) {
p[[i]] <- plot_ly(type = 'violin') %>%
add_trace(x = df$day[df$sex == 'Male' & df$day == unique(df$day)[i]],
y = df$total_bill[df$sex == 'Male' & df$day == unique(df$day)[i]],
hoveron = "points+kde",
legendgroup = 'M',
scalegroup = 'M',
name = 'M',
side = 'negative',
box = list(visible = T),
points = 'all',
pointpos = pointposMale[i],
jitter = 0,
scalemode = 'count',
meanline = list(visible = T),
color = I("#8dd3c7"),
marker = list(line = list(width = 2, color = "#8dd3c7"),
symbol = 'line-ns'),
showlegend = showLegend[i]) %>%
add_trace(x = df$day[df$sex == 'Female' & df$day == unique(df$day)[i]],
y = df$total_bill[df$sex == 'Female' & df$day == unique(df$day)[i]],
hoveron = "points+kde",
legendgroup = 'F',
scalegroup = 'F',
name = 'F',
side = 'positive',
box = list(visible = T),
points = 'all',
pointpos = pointposFemale[i],
jitter = 0,
scalemode = 'count',
meanline = list(visible = T),
color = I("#bebada"),
marker = list(line = list(width = 2, color = "#bebada"),
symbol = 'line-ns'),
showlegend = showLegend[i]) %>%
layout(title = "Total bill distribution<br><i>scaled by number of bills per gender",
yaxis = list(zeroline = F),
xaxis = list(range=c(-0.8,0.8)),
violingap = 0,
violingroupgap = 0,
violinmode = 'overlay',
legend = list(tracegroupgap = 0))
}
t<-subplot(p[[1]],p[[2]],p[[3]],p[[4]],nrows = 1,shareY = TRUE, margin = 0)
tdata<-data.frame(plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = mean(len)),
plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = sd(len))%>% select(length)) %>%
rename("sd"=length.1) %>%
mutate(dose=as.factor(.$dose))
p <- plot_ly(data = data[which(data$supp == 'OJ'),],
x = ~dose,
y = ~length,
type = 'bar',
name = 'OJ',
error_y = ~list(array = sd,
color = '#000000')) %>%
add_trace(data = data[which(data$supp == 'VC'),],
name = 'VC')
pdata<-data.frame(plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = mean(len)),
plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = sd(len))%>% select(length)) %>%
rename("sd"=length.1) %>%
mutate(dose=as.factor(.$dose))
p <- plot_ly(data[which(data$supp == 'OJ'),],
x = ~dose,
y = ~length,
type = 'scatter',
mode = 'markers',
name = 'OJ',
error_y = ~list(array = sd, color = '#000000')) %>%
add_trace(data = data[which(data$supp == 'VC'),], name = 'VC')
pdata("ToothGrowth")
data<-data.frame(plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = mean(len)),
plyr::ddply(ToothGrowth, c("supp", "dose"),
summarise,
length = sd(len))%>% select(length)) %>%
rename("sd"=length.1) %>%
mutate(dose=as.factor(.$dose))
p <- plot_ly(data = data[which(data$supp == 'OJ'),],
x = ~dose,
y = ~length,
type = 'scatter',
mode = 'line + markers',
name = 'OJ',
error_y = ~list(array = sd, color = '#000000')) %>%
add_trace(data = data[which(data$supp == 'VC'),], name = 'VC')
pUna matriz de scatterplots, esta asociada a \(n\) matrices númericas \(X^{1},X^{2},...,X^{n}\) de la misma longuitud.
p <- plot_ly()%>%
add_trace( dimensions = list(list(label='string-1', values=X1),
list(label='string-2', values=X2),
.
.
.
list(label='string-n', values=Xn)),
text=text,
marker=list(...))
pLa etiqueta en cada dimensión se asigna a los títulos de los ejes de la celda de cada matriz correspondiente.
El texto es una cadena única asignada a todos los puntos mostrados por splom o una lista de cadenas de la misma longitud que las dimensiones, \(X_{i}\). El text[k] es la información sobre herramientas para el \(k^{th}\) punto en cada celda.
El marker establece los atributos de los marcadores en todos los gráficos de dispersión.
Se Define una escala de colores discreta con tres colores correspondientes a las tres clases de flores:
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/iris-data.csv')
pl_colorscale=list(c(0.0, '#19d3f3'),
c(0.333, '#19d3f3'),
c(0.333, '#e763fa'),
c(0.666, '#e763fa'),
c(0.666, '#636efa'),
c(1, '#636efa'))
axis = list(showline=FALSE,
zeroline=FALSE,
gridcolor='#ffff',
ticklen=4)
p <- df %>%
plot_ly() %>%
add_trace(type = 'splom',
dimensions = list(list(label='sepal length', values=~sepal.length),
list(label='sepal width', values=~sepal.width),
list(label='petal length', values=~petal.length),
list(label='petal width', values=~petal.width)),
text=~class,
marker = list(color = as.integer(df$class),
colorscale = pl_colorscale,
size = 7,
line = list(width = 1, color = 'rgb(230,230,230)'))) %>%
layout(title= 'Iris Data set',
hovermode='closest',
dragmode= 'select',
plot_bgcolor='rgba(240,240,240, 0.95)',
xaxis=list(domain=NULL,
showline=F,
zeroline=F,
gridcolor='#ffff', ticklen=4),
yaxis=list(domain=NULL,
showline=F,
zeroline=F,
gridcolor='#ffff',
ticklen=4),
xaxis2=axis,
xaxis3=axis,
xaxis4=axis,
yaxis2=axis,
yaxis3=axis,
yaxis4=axis)
pLos gráficos de dispersión en la diagonal principal se pueden eliminar configurando diagonal=list(visible=FALSE)
Para trazar solo la mitad inferior / superior del splom se cambia el valor predeterminado showlowerhalf=TRUE/ showupperhalf=FALSE:
Cada lista en las dimensiones tiene una clave, visible, establecida de forma predeterminada en visible=TRUE. Se puede elegir eliminar una variable de splom, configurando visible=FALSE su dimensión correspondiente. En este caso, la cuadrícula predeterminada asociada a la matriz de diagrama de dispersión mantiene su número de celdas, pero las celdas en la fila y columna correspondientes a la dimensión falsa visible están vacías:
El conjunto de datos sobre diabetes se descarga de kaggle . Se utiliza para predecir la aparición de diabetes en base a 8 medidas de diagnóstico. El archivo de diabetes contiene las medidas de diagnóstico para 768 pacientes, que están etiquetados como no diabéticos (Outcome = 0), respectivamente, diabéticos (Outcome = 1). El splom asociado a las 8 variables puede ilustrar la fuerza de la relación entre pares de medidas para pacientes diabéticos / no diabéticos.
Se define una escala de colores discreta con dos colores: azul para no diabéticos y rojo para diabéticos:
df = read.csv('https://raw.githubusercontent.com/plotly/datasets/master/diabetes.csv')
pl_colorscale = list(c(0.0, '#119dff'),
c(0.5, '#119dff'),
c(0.5, '#ef553b'),
c(1, '#ef553b'))
axis = list(showline=FALSE,
zeroline=FALSE,
gridcolor='#ffff',
ticklen=4,
titlefont=list(size=13))
p <- df %>%
plot_ly() %>%
add_trace(type = 'splom',
dimensions = list(list(label='Pregnancies', values=~Pregnancies),
list(label='Glucose', values=~Glucose),
list(label='BloodPressure', values=~BloodPressure),
list(label='SkinThickness', values=~SkinThickness),
list(label='Insulin', values=~Insulin),
list(label='BMI', values=~BMI),
list(label='DiabPedigreeFun', values=~DiabetesPedigreeFunction),
list(label='Age', values=~Age)),
text=~factor(Outcome, labels=c("non-diabetic","diabetic")),
diagonal=list(visible=F),
marker = list(color = ~Outcome,
colorscale = pl_colorscale,
size = 5,
line = list(width = 1, color = 'rgb(230,230,230)'))) %>%
layout(title = "Scatterplot Matrix (SPLOM) for Diabetes Dataset<br>Data source: <a href='https://www.kaggle.com/uciml/pima-indians-diabetes-database/data'>[1]</a>",
hovermode='closest',
dragmode = 'select',
plot_bgcolor='rgba(240,240,240, 0.95)',
xaxis=list(domain=NULL,
showline=F,
zeroline=F,
gridcolor='#ffff',
ticklen=4,
titlefont=list(size=13)),
yaxis=list(domain=NULL,
showline=F,
zeroline=F,
gridcolor='#ffff',
ticklen=4,
titlefont=list(size=13)),
xaxis2=axis,
xaxis3=axis,
xaxis4=axis,
xaxis5=axis,
xaxis6=axis,
xaxis7=axis,
xaxis8=axis,
yaxis2=axis,
yaxis3=axis,
yaxis4=axis,
yaxis5=axis,
yaxis6=axis,
yaxis7=axis,
yaxis8=axis)
pLos histogramas 2D requieren \(x/y\), pero a diferencia de los mapas de calor, \(z\) es opcional. Si \(z\) no se proporciona, el binning se produce en el navegador.
p <- plot_ly(z = matrix(c(10, 10.625, 12.5, 15.625, 20, 5.625, 6.25, 8.125,
11.25, 15.625, 2.5, 3.125, 5, 8.125, 12.5, 0.625,
1.25, 3.125, 6.25, 10.625, 0, 0.625, 2.5, 5.625, 10), nrow=5, ncol=5),
type = 'contour',
colorscale = 'Jet',
autocontour = F,
contours = list(start = 0,
end = 8,
size = 2))
pp1 <- plot_ly(z = matrix(c(2, 4, 7, 12, 13, 14, 15, 16, 3, 1, 6, 11, 12, 13,
16, 17, 4, 2, 7, 7, 11, 14, 17, 18, 5, 3, 8, 8, 13,
15, 18, 19, 7, 4, 10, 9, 16, 18, 20, 19, 9, 10, 5, 27,
23, 21, 21, 21, 11, 14, 17, 26, 25, 24, 23, 22), nrow=7, ncol=8),
type = "contour",
autocontour = TRUE,
contours = list(end = 26,
size = 2,
start = 2),
line = list(smoothing = 0))
p2 <- plot_ly(z = matrix(c(2, 4, 7, 12, 13, 14, 15, 16, 3, 1, 6, 11, 12, 13,
16, 17, 4, 2, 7, 7, 11, 14, 17, 18, 5, 3, 8, 8, 13,
15, 18, 19, 7, 4, 10, 9, 16, 18, 20, 19, 9, 10, 5, 27,
23, 21, 21, 21, 11, 14, 17, 26, 25, 24, 23, 22), nrow=7, ncol=8),
type = "contour",
autocontour = TRUE,
contours = list(end = 26,
size = 2,
start = 2),
line = list(smoothing = 0.85))
p <- subplot(p1,p2)
pp <- plot_ly(z = matrix(c(2, 4, 7, 12, 13, 14, 15, 16, 3, 1, 6, 11, 12, 13,
16, 17, 4, 2, 7, 7, 11, 14, 17, 18, 5, 3, 8, 8, 13,
15, 18, 19, 7, 4, 10, 9, 16, 18, 20, 19, 9, 10, 5, 27,
23, 21, 21, 21, 11, 14, 17, 26, 25, 24, 23, 22), nrow=7, ncol=8),
type = "contour",
contours = list(coloring = 'heatmap'))
pdata("mtcars")
data.loess <- loess(qsec ~ wt * hp, data = mtcars)
# Create a sequence of incrementally increasing (by 0.3 units) values for both wt and hp
xgrid <- seq(min(mtcars$wt), max(mtcars$wt), 0.3)
ygrid <- seq(min(mtcars$hp), max(mtcars$hp), 0.3)
# Generate a dataframe with every possible combination of wt and hp
data.fit <- expand.grid(wt = xgrid, hp = ygrid)
# Feed the dataframe into the loess model and receive a matrix output with estimates of acceleration for each combination of wt and hp
mtrx3d <- predict(data.loess, newdata = data.fit)%>%
melt(id.vars = c('wt', 'hp'), measure.vars = 'qsec') %>%
rename('qsec'=value) %>%
mutate(wt = as.numeric(str_sub(.$wt, str_locate(.$wt, '=')[1,1] + 1)),
hp = as.numeric(str_sub(.$hp, str_locate(.$hp, '=')[1,1] + 1)))
p <- plot_ly(mtrx3d,
x = ~wt,
y = ~hp,
z = ~qsec,
type = "contour",
width = 600,
height = 500)
pdata<- data.frame(x = rnorm(200),
y = rnorm(200))
p <- subplot(plot_ly(x = data$x,
type = "histogram"),
plotly_empty(),
plot_ly(x = data$x,
y = data$y,
type = "histogram2dcontour"),
plot_ly(y = data$y,
type = "histogram",
mode='markers',
marker=list(color="yellow")),
nrows = 2,
heights = c(0.2, 0.8),
widths = c(0.8, 0.2),
margin = 0,
shareX = TRUE,
shareY = TRUE,
titleX = FALSE,
titleY = FALSE)%>%
layout(showlegend = FALSE)
pEste ejemplo muestra cómo cortar el gráfico de superficie en la posición deseada para cada uno de los ejes \(x\), \(y\) y \(z\).
contours.x.start establece el valor inicial del nivel de contorno,
end establece el final y
size establece el step entre cada nivel de contorno.
data<- data.frame(x = c(1,2,3,4,5),
y = c(1,2,3,4,5))
z = rbind(c(0, 1, 0, 1, 0),
c(1, 0, 1, 0, 1),
c(0, 1, 0, 1, 0),
c(1, 0, 1, 0, 1),
c(0, 1, 0, 1, 0))
p<-plot_ly( x = ~data$x,
y = ~data$y,
z = ~z,
type = 'surface',
contours = list(x = list(show = TRUE,
start = 1.5,
end = 2,
size = 0.04,
color = 'white'),
z = list(show = TRUE,
start = 0.5,
end = 0.8,
size = 0.05))) %>%
layout(scene = list(xaxis = list(nticks = 20),
zaxis = list(nticks = 4),
camera = list(eye = list(x = 0, y = -1, z = 0.5)),
aspectratio = list(x = .9, y = .8, z = 0.2)))
pz <- c(c(8.83,8.89,8.81,8.87,8.9,8.87),
c(8.89,8.94,8.85,8.94,8.96,8.92),
c(8.84,8.9,8.82,8.92,8.93,8.91),
c(8.79,8.85,8.79,8.9,8.94,8.92),
c(8.79,8.88,8.81,8.9,8.95,8.92),
c(8.8,8.82,8.78,8.91,8.94,8.92),
c(8.75,8.78,8.77,8.91,8.95,8.92),
c(8.8,8.8,8.77,8.91,8.95,8.94),
c(8.74,8.81,8.76,8.93,8.98,8.99),
c(8.89,8.99,8.92,9.1,9.13,9.11),
c(8.97,8.97,8.91,9.09,9.11,9.11),
c(9.04,9.08,9.05,9.25,9.28,9.27),
c(9,9.01,9,9.2,9.23,9.2),
c(8.99,8.99,8.98,9.18,9.2,9.19),
c(8.93,8.97,8.97,9.18,9.2,9.18))
dim(z) <- c(15,6)
z2 <- z + 1
z3 <- z - 1
p <- plot_ly(showscale = FALSE) %>%
add_surface(z = ~z) %>%
add_surface(z = ~z2, opacity = 0.98) %>%
add_surface(z = ~z3, opacity = 0.98)
pPlotly R Graphing Library | R | Plotly. (n.d.). Retrieved August 5, 2020, from https://plotly.com/r/